Reputation: 5673
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 ?
Upvotes: 2
Views: 252
Reputation: 887691
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]
Upvotes: 3