简体   繁体   中英

Why is any() only defined for a numeric and not logical data.frame?

This appears to be quite surprising:

df1 <- data.frame(A=TRUE, B=FALSE)
df2 <- data.frame(A=1, B=2)

> any(df1)
Error in FUN(X[[i]], ...) :
  only defined on a data frame with all numeric variables

> any(df2)
[1] TRUE

This doesn't seem to be a bug because the error correctly states that any() will only work in the case where all variables within a data.frame are numeric.

But what is the reason for any() to work on all numeric variables and not when values are all logical?

any can work if it is vector as the documentation says

Given a set of logical vectors, is at least one of the values true?

In the OP's post, both examples are not vector s. The first is a data.frame with logical columns. If we go by way to satisfy the documentation ie create a logical vector, either convert to matrix (as a matrix is a vector anyway with some dim attributes)

any(as.matrix(df1))
#[1] TRUE

Or change it to a vector by unlist ing the list (a data.frame is a list of vector s aka columns of same length)

any(unlist(df1))

In the second case, there is a warning and it is doing some coercing

any(df2)
#[1] TRUE

Warning message: In any(c(1, 2), na.rm = FALSE) : coercing argument of type 'double' to logical

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM