The Art of R Programming

(WallPaper) #1
This also has the advantage of not destroying the names inwu, in case
they are needed later. If they will not be needed later, we could simply
assign back towuinstead of towunin the preceding statement.

4.4 Applying Functions to Lists...................................................


Two functions are handy for applying functions to lists:lapplyandsapply.

4.4.1 Using the lapply() and sapply() Functions..........................


The functionlapply()(forlist apply) works like the matrixapply()function,
calling the specified function on each component of a list (or vector coerced
to a list) and returning another list. Here’s an example:

> lapply(list(1:3,25:29),median)
[[1]]
[1] 2

[[2]]
[1] 27

R appliedmedian()to 1:3 and to 25:29, returning a list consisting of 2 and 27.
In some cases, such as the example here, the list returned bylapply()
could be simplified to a vector or matrix. This is exactly whatsapply()(for
simplified [l]apply) does.

> sapply(list(1:3,25:29),median)
[1] 2 27

You saw an example of matrix output in Section 2.6.2. There, we
applied a vectorized, vector-valued function—a function whose return
value is a vector, each of whose components is vectorized— to a vector
input. Usingsapply(), rather than applying the function directly, gave us
the desired matrix form in the output.

4.4.2 Extended Example: Text Concordance, Continued.................


The text concordance creator,findwords(), which we developed in Sec-
tion 4.2.4, returns a list of word locations, indexed by word. It would be
nice to be able to sort this list in various ways.
Recall that for the input filetestconcorda.txt, we got this output:

$the
[1] 1 5 63

$here
[1] 2

Lists 95
Free download pdf