
i
i
“K23166” — 2015/1/28 — 9:35 — page 45 — #71
i
i
i
i
i
i
Chapter 4
Programming and operating
system interface
This chapter reviews programming functions as well as interactions with the underlying
operating system.
4.1 Control flow, programming, and data generation
4.1.1 Looping
Example: 11.2
x = numeric(k) # create placeholder
for (i in 1:length(x)) {
x[i] = rnorm(1) # this is slow and inefficient!
}
or (preferably)
x = rnorm(k) # this is far better
Note: Most tasks in R that could be written as a loop are often dramatically faster if they
are encoded as a vector operation (as in the second and preferred option above). Examples
of situations where loops are particularly ...