Vectorization over Loops
Vectorization means doing an action on a whole list at once instead of item by item in a loop. It is like pouring a full bucket rather than moving water one spoonful at a time, and it is faster in R.
In this page:
Syntax
result <- vector_name * 2 # vectorized
result <- function_name(vector_name)
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Growing a vector in a loop with
result <- c(result, x^2), which gets slow because it copies each time. - Writing a loop for something like
sumornumbers^2, when a vectorised form is shorter and faster. - Using
ifon vectors inside a vectorised approach, whenifelse()is needed.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: