The Art of R Programming

(WallPaper) #1

4.4.3 Extended Example: Back to the Abalone Data.....................


Let’s use thelapply()function in our abalone gender example in Sec-
tion 2.9.2. Recall that at one point in that example, we wished to know the
indices of the observations that were male, female, and infant. For an easy
demonstration, let’s use the same test case: a vector of genders.

g <- c("M","F","F","I","M","M","F")

A more compact way of accomplishing our goal is as follows:

> lapply(c("M","F","I"),function(gender) which(g==gender))
[[1]]
[1]156

[[2]]
[1]237

[[3]]
[1] 4

Thelapply()function expects its first argument to be a list. Here it was a
vector, butlapply()willcoercethat vector to a list form. Also,lapply()expects
its second argument to be a function. This could be the name of a function,
as you saw before, or the actual code, as we have here. This is ananonymous
function, which you’ll learn more about in Section 7.13.
Thenlapply()calls that anonymous function on"M", then on"F", and
then on"I". In that first case, the function calculateswhich(g=="M"), giving us
the vector of indices ingof the males. After determining the indices for the
females and infants,lapply()will return the three vectors in a list.
Note that even though the object of our main attention is the vectorg
of genders, it is not the first argument in thelapply()call in the example.
Instead, that argument is an innocuous-looking vector of the three possible
gender encodings. By contrast,gis mentioned only briefly in the function,
as the second actual argument. This is a common situation in R. An even
better way to do this will be presented in Section 6.2.2.

4.5 Recursive Lists..............................................................


Lists can be recursive, meaning that you can have lists within lists. Here’s an
example:

> b <- list(u = 5,v=12)
> c <- list(w = 13)
> a <- list(b,c)
>a
[[1]]
[[1]]$u

Lists 99
Free download pdf