Chapter 9. Advanced Looping
R’s looping capability goes far beyond the three standard-issue loops seen in the last chapter. It gives you the ability to apply functions to each element of a vector, list, or array, so you can write pseudo-vectorized code where normal vectorization isn’t possible. Other loops let you calculate summary statistics on chunks of data.
Chapter Goals
After reading this chapter, you should:
- Be able to apply a function to every element of a list or vector, or to every row or column of a matrix
- Be able to solve split-apply-combine problems
-
Be able to use the
plyr
package
Replication
Cast your mind back to Chapter 4 and the rep
function. rep
repeats its input several times. Another related function, replicate
, calls an expression several times. Mostly, they do exactly the same thing. The difference occurs when random number generation is involved. Pretend for a moment that the uniform random number generation function, runif
, isn’t vectorized. rep
will repeat the same random number several times, but replicate
gives a different number each time (for historical reasons, the order of the arguments is annoyingly back to front):
rep(
runif(
1
),
5
)
## [1] 0.04573 0.04573 0.04573 0.04573 0.04573
replicate(
5
,
runif(
1
))
## [1] 0.5839 0.3689 0.1601 0.9176 0.5388
replicate
comes into its own in more complicated examples: its main use is in Monte Carlo analyses, where you repeat an analysis a known number of times, and each iteration is independent of the others.
This next example ...
Get Learning R now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.