The Art of R Programming

(WallPaper) #1
Thus, the following:

z*z>8

is really this:

">"(z*z,8)

In other words, we are applying a function to vectors—yet another case
of vectorization, no different from the others you’ve seen. And thus the
result is a vector—in this case, a vector of Booleans. Then the resulting
Boolean values are used to cull out the desired elements ofz:

> z[c(TRUE,FALSE,TRUE,TRUE)]
[1] 5 -3 8

This next example will place things into even sharper focus. Here, we
will again define our extraction condition in terms ofz, but then we will use
the results to extract from another vector,y, instead of extracting fromz:

> z <- c(5,2,-3,8)
>j<-z*z>8
>j
[1] TRUE FALSE TRUE TRUE
> y <- c(1,2,30,5)
> y[j]
[1] 1 30 5

Or, more compactly, we could write the following:

> z <- c(5,2,-3,8)
> y <- c(1,2,30,5)
> y[z*z>8]
[1] 1 30 5

Again, the point is that in this example, we are using one vector,z,to
determine indices to use in filteringanothervector,y. In contrast, our earlier
example usedzto filter itself.
Here’s another example, this one involving assignment. Say we have a
vectorxin which we wish to replace all elements larger thana3witha0.We
can do that very compactly—in fact, in just one line:

>x[x>3]<-0

46 Chapter 2

Free download pdf