← Back to R Course | Chapter 12: Best Practices | Lesson 2 of 6

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:

  1. Vectorization over Loops
Syntax
r
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

markup
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")
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
  1. Growing a vector in a loop with result <- c(result, x^2), which gets slow because it copies each time.
  2. Writing a loop for something like sum or numbers^2, when a vectorised form is shorter and faster.
  3. Using if on vectors inside a vectorised approach, when ifelse() is needed.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.