The Art of R Programming

(WallPaper) #1

2.5 Using all() and any()........................................................


Theany()andall()functions are handy shortcuts. They report whether any
or all of their arguments areTRUE.

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

For example, suppose that R executes the following:

> any(x > 8)

It first evaluatesx>8, yielding this:

(FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,FALSE,TRUE,TRUE)

Theany()function then reports whether any of those values isTRUE. The
all()function works similarly and reports ifallof the values areTRUE.

2.5.1 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,
there is a run of length 3 starting at index 4, and runs of length 2 beginning
at indices 4, 5, and 8. So the callfindruns(c(1,0,0,1,1,1,0,1,1),2)to our func-
tion to be shown below returns (4,5,8). Here is the code:

1 findruns <- function(x,k) {
2 n <- length(x)
3 runs <- NULL
4 for (i in 1:(n-k+1)) {
5 if (all(x[i:(i+k-1)]==1)) runs <- c(runs,i)
6 }
7 return(runs)
8 }

Vectors 35
Free download pdf