The function all() is designed to test a vector or a data frame or a variable within a data frame, and make sure all its values follow a certain rule or rules.

If all the values obey to this rule or rules, the result will be TRUE, otherwise the result will be FALSE.

It is important to note that it is always advisable to use the command na.rm=TRUE, to avoid this possible influence of missing values and thus harming the result.

The function any() is quite similar, and is designed to test a vector or a data frame or a variable within a data frame, and make sure any of its values, or at least one of its follow a certain rule or rules.

In this case as well, if any of the values follow this rule or set of rules, the result will be TRUE, otherwise the result will be FALSE.

Also, in this case too, it is preferred to use the command na.rm=TRUE, to avoid this possible influence of missing values and thus disrupting the result.

Example 1: Using a vector with 1 term:

a <- c(1,2,3,4,5)
all(a > 2, na.rm=TRUE)
any(a > 2, na.rm=TRUE)

The result for the all() function in this case would be FALSE, because of 1 and 2, that do not follow the rule, and the result of the any() function would be TRUE because at least 1 element in a satisfies the rule.

Example 2: Using a vector with 2 terms:

a <- c(1,2,3,4,5)
all(a > -2 | a < 5.1, na.rm=TRUE)
all(a > -2 & a < 5.1, na.rm=TRUE)
any(a > -2 | a < 5.1, na.rm=TRUE)
any(a > -2 & a < 5.1, na.rm=TRUE)

In all 4 cases the result would be TRUE:

The reason is that all five elements of a fulfill the rules stated in the logical expression.

Example 3: Using a dataframe:

a <- c(1,2,3)
b <- c(4,5,6)

ab <- data.frame(a,b)
all(ab$a > 2 & ab$b < 10, na.rm = T)
any(ab$a > 2 & ab$b < 10, na.rm = T)

The result of the all() expression is FALSE due to 1 that belongs to a, and the result of the any() function is TRUE because there’s at least one element that fulfills both rules.