Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

r - data.table fifelse giving wrong warning?

I found warning difference using fifelse from data.table library:

set.seed(123)
df <- data.table(ID = rep(1:10,each = 2),x = sample(c(1,NA),20,replace = T))

test1 <- df[,fifelse(any(!is.na(x)),max(x,na.rm = T),as.numeric(NA)),by = ID]

produces a warning:

Warning messages 1: In max(x, na.rm = T) : no non-missing arguments to max; returning -Inf 2: In max(x, na.rm = T) : no non-missing arguments to max; returning -Inf

while:

test2 <- df[,ifelse(any(!is.na(x)),max(x,na.rm = T),as.numeric(NA)),by = ID]

don't. And the two results are identical:

identical(test1,test2)
[1] TRUE

And there is no -Inf in the result. What does this mean ?

question from:https://stackoverflow.com/questions/65833177/data-table-fifelse-giving-wrong-warning

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It may be better to use if/else as the input is of length 1

df[, if(any(!is.na(x))) max(x, na.rm = TRUE) else NA_real_, by = ID]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...