any, all

Check whether any or all of the elements of a vector are TRUE. Both functions also accept multiple objects simultaneously. Those objects that aren’t logical are coerced (forced) to take a logical form.
any(…, na.rm=FALSE)
  • – One or more R objects that are to be checked.
  • na.rm – Indicate whether NA values should be ignored.
all(…, na.rm=FALSE)
  • – One or more R objects that are to be checked.
  • na.rm – Indicate whether NA values should be ignored.

Example. I usually use any and all to check logical statements applied across a vector, check for NA values, or to examine a vector of logical values. The last example listed below shows a vector with zero elements; the output of any and all in this case may at first be confusing. In that vector, all zero of the values are TRUE, but there aren’t any TRUE values to be found.
> set.seed(5)
> 
> x <- rnorm(1000)
> range(x)
[1] -3.498059  3.401872
> any(x > 3)
[1] TRUE
> any(is.na(x))
[1] FALSE
> all(x > -3)
[1] FALSE
> all(x > -3.5)
[1] TRUE
> 
> 
> x <- sample(c(TRUE, FALSE), 3, TRUE)
> x
[1]  TRUE FALSE FALSE
> any(x)
[1] TRUE
> all(x)
[1] FALSE
> 
> x <- rep(FALSE, 3)
> x
[1] FALSE FALSE FALSE
> any(x)
[1] FALSE
> all(x)
[1] FALSE
> 
> x <- rep(TRUE, 3)
> x
[1] TRUE TRUE TRUE
> any(x)
[1] TRUE
> all(x)
[1] TRUE
> 
> x <- c()
> x
NULL
> any(x)
[1] FALSE
> all(x)
[1] TRUE

Leave a Reply