Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 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 Answer

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...