So we are used to say to every R new user that \"apply
isn\'t vectorized, check out the Patrick Burns R Inferno Circle 4\" which says (I quote):
To me, vectorisation is primarily about making your code easier to write and easier to understand.
The goal of a vectorised function is to eliminate the book-keeping associated with a for loop. For example, instead of:
means <- numeric(length(mtcars))
for (i in seq_along(mtcars)) {
means[i] <- mean(mtcars[[i]])
}
sds <- numeric(length(mtcars))
for (i in seq_along(mtcars)) {
sds[i] <- sd(mtcars[[i]])
}
You can write:
means <- vapply(mtcars, mean, numeric(1))
sds <- vapply(mtcars, sd, numeric(1))
That makes it easier to see what's the same (the input data) and what's different (the function you're applying).
A secondary advantage of vectorisation is that the for-loop is often written in C, rather than in R. This has substantial performance benefits, but I don't think it's the key property of vectorisation. Vectorisation is fundamentally about saving your brain, not saving the computer work.