0.012 0.000 0.015
> system.time(
+{
+ c <- 0
+ for (i in 1:length(x))
+ if (x[i] %% 2 == 1) c <- c+1
+ return(c)
+}
+)
user system elapsed
0.308 0.000 0.310
You might wonder whether it matters in this case, since even the loop
version of the code took less than a second to run. But if this code had been
part of an enclosing loop, with many iterations, the difference could be
important indeed.
Examples of other vectorized functions that may speed up your code
areifelse(),which(),where(),any(),all(),cumsum(), andcumprod(). In the
matrix case, you can userowSums(),colSums(), and so on. In “all possible
combinations” types of settings,combin(),outer(),lower.tri(),upper.tri(),
orexpand.grid()may be just what you need.
Thoughapply()eliminates an explicit loop, it is actually implemented in
R rather than C and thus will usually not speed up your code. However, the
otherapplyfunctions, such aslapply(), can be very helpful in speeding up
your code.
14.2.2 Extended Example: Achieving Better Speed in a Monte Carlo
Simulation
In some applications, simulation code can run for hours, days, or even
months, so speedup methods are of high interest. Here, we’ll look at two
simulation examples.
To begin, let’s consider the following code from Section 8.6:
sum <- 0
nreps <- 100000
for (i in 1:nreps) {
xy <- rnorm(2) # generate 2 N(0,1)s
sum <- sum + max(xy)
}
print(sum/nreps)
Here’s a revision (hopefully faster):
nreps <- 100000
xymat <- matrix(rnorm(2*nreps),ncol=2)
308 Chapter 14