How to Use all() and any() Functions in R

The all() function in R is “used to check if all values in a vector evaluate to TRUE for some expression”.

The any() function in R is “used to check if any values in a vector evaluate to TRUE for some expression”.

Syntax

all(x, na.rm = FALSE)

any(x, na.rm = FALSE)

Parameters

  1. x: It is a vector.
  2. na.rm: A logical value indicating whether to remove missing values (NA) from the input vector before checking.

Example 1: Use all() and any() with Vector

vec <- c(10, 11, 19, 21, 46)

#check if all values are less than 20
all(vec < 20)

#check if any values are less than 20
any(vec < 20)

Output

[1] FALSE
[1] TRUE

Example 2: Use all() with NA Values

If you use the all() function with a vector with NA values, you may receive NA as an output.

vec <- c(10, 11, NA, 21, NA)

# check if all values are less than 25
all(vec < 25)

Output

[1] NA

To prevent this, specify the na.rm=TRUE parameter to remove the NA values from the vector before checking if all values meet some condition.

vec <- c(10, 11, NA, 21, NA)

# check if all values are less than 25
all(vec < 25, na.rm = TRUE)

Output

[1] TRUE

Example 3: Use all() and any() with Data Frame Columns

You can use all() and any() functions to evaluate expressions for data frame columns.

df <- data.frame(
  runs = c(30, 40, 50, 60),
  balls = c(20, 25, 40, 45),
  out = c(1, 0, 0, NA)
)

all(df$runs < 40, na.rm = TRUE)

any(is.na(df$out))

Output

[1] FALSE
[1] TRUE

That’s it.

Leave a Comment