Vectorization over Loops
In this page:
Vectorization over Loops
R is optimized for vectorized operations -- applying a function to an entire vector at once -- which run much faster than an equivalent element-by-element for loop, since vectorized operations are implemented in optimized C code under the hood. Prefer v * 2, sum(v), or sapply() over manually looping and appending to a result vector. This is one of the most important performance habits in R.
Warning: Growing a vector inside a loop with result <- c(result, new_value) is a classic R performance trap -- it reallocates memory on every iteration.
Example: Vectorization over Loops
numbers <- 1:1000000
# Vectorized (fast, idiomatic)
squared_vectorized <- numbers^2
# A loop would work but be far slower for this size of data
cat("First 5 squared values:", head(squared_vectorized, 5), "\n")
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: