Using all() and any()

The any() and all() functions are handy shortcuts. They report whether any or all of their arguments are TRUE.

> x <- 1:10
> any(x > 8)
[1] TRUE
> any(x > 88)
> all(x > 88)
> all(x > 0)
[1] TRUE

For example, suppose that R executes the following:

> any(x > 8)

It first evaluates x > 8, yielding this:


The any() function then reports whether any of those values is TRUE. The all() function works similarly and reports if all of the values are TRUE.

Extended Example: Finding Runs of Consecutive Ones

Suppose that we are interested in finding runs of consecutive 1s in vectors that consist just of 1s and 0s. In the vector (1,0,0,1,1,1,0,1,1), for instance, ...

Get The Art of R Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.