01 / 20

Vectorization vs.
Loops in R

Learn why R is designed to operate on whole vectors at once and when you should choose vectorization over explicit loops for cleaner, faster code.

R Programming

What Is a Loop?

A loop is an instruction that tells R to repeat a block of code once for each element in a collection. The most common type is the for loop:

# Square every number in a vector result <- numeric(length(x)) for (i in seq_along(x)) { result[i] <- x[i]^2 }

What Is Vectorization?

Vectorization means applying an operation to an entire vector at once rather than looping through its elements. R's built-in functions are designed to work this way:

# Square every number — vectorized result <- x^2

Why Does This Matter?

★ Speed
Vectorized code can be 10 to 100 times faster because the heavy lifting runs in compiled C, not interpreted R.
★ Readability
One expressive line is easier to read and debug than a multi-line loop with indexing variables.
★ Idiomatic R
R was built for vectors. Using vectorization aligns with the language's design and community conventions.

The Core Principle

Loop Approach
\( x[1] \)
\( x[2] \)
\( x[3] \)
\( x[n] \)
... op op op op
\( n \) separate R calls
Vectorized Approach
\( x[1] \)
\( x[2] \)
...
\( x[n] \)
op 1 compiled C call

Under the Hood

R is an interpreted language. Each line you write is translated at runtime, which is slow. Vectorized functions delegate work to pre-compiled C/Fortran routines that run at native speed.

R Interpreter Slow per element loop Element-by-Element Overhead per iteration Vectorized Function Single dispatch to C Compiled C Loop Near-zero overhead vs.

Loop vs. Vectorized: Side by Side

for Loop Vectorized
Syntax Multi-line with index Single expression
Speed Slow (interpreted) Fast (compiled C)
Readability Verbose Concise and clear
When to use Iteration depends on prior result Same operation on every element
R convention Last resort Preferred

When to Vectorize

1
Arithmetic on vectors: x + y, x * 2, x^2 all work element-wise automatically.
2
Built-in math functions: sqrt(x), log(x), abs(x), round(x) accept entire vectors.
3
Logical comparisons: x > 5 returns a vector of TRUE/FALSE values without a loop.
4
String operations: paste0(), toupper(), gsub() process character vectors at once.

When Loops Are Actually Needed

Some tasks truly require the result of one iteration to feed the next. These are called sequential dependencies:

# Cumulative product where each step depends on the last balance <- 1000 for (i in seq_along(rates)) { balance <- balance * (1 + rates[i]) }

Decision Flowchart

Does each iteration depend on the previous? YES Use a Loop Or Reduce() / accumulate() functional alternatives NO Vectorize!

How to Apply This

1
Spot the pattern: "Am I doing the same thing to every element?"
2
Check for dependency: Does element \( i \) need the result from element \( i-1 \)?
3
Find the vectorized function: Arithmetic operators, ifelse(), sapply(), cumsum(), etc.
4
Replace the loop with the vectorized equivalent and verify with a small test.
5
If no vectorized path exists, keep the loop: clarity beats cleverness.

Example 1: Simple Arithmetic

✕ Loop version
temps_f <- numeric(length(temps_c)) for (i in seq_along(temps_c)) { temps_f[i] <- temps_c[i] * 9/5 + 32 }
✓ Vectorized version
temps_f <- temps_c * 9/5 + 32

Example 2: Conditional Logic

Task: label each score as "Pass" or "Fail" based on a threshold of 60.

✕ Loop version
labels <- character(length(scores)) for (i in seq_along(scores)) { if (scores[i] >= 60) { labels[i] <- "Pass" } else { labels[i] <- "Fail" } }
✓ Vectorized version
labels <- ifelse(scores >= 60, "Pass", "Fail")

Example 3: When a Loop Wins

Task: simulate a random walk where each position equals the previous position plus a random step.

steps <- sample(c(-1, 1), 100, replace = TRUE) pos <- numeric(100) pos[1] <- steps[1] for (i in 2:100) { pos[i] <- pos[i - 1] + steps[i] }

Common Mistakes

✕ Growing a Vector in a Loop
Using c(result, newval) inside a loop copies the entire vector each iteration: \( O(n^2) \) time.
✕ Using a Loop for Simple Math
Writing for(i in 1:n) y[i] <- x[i] + 1 when y <- x + 1 does the same thing instantly.
✕ Forcing Vectorization on Dependencies
Trying to avoid a loop when each step needs the previous result leads to incorrect or convoluted code.

Summary Cheat Sheet

Task Loop? Vectorized Alternative
Add 10 to every element No x + 10
Conditional labels No ifelse()
Apply function to each column No sapply() / lapply()
Running total Maybe cumsum()
State depends on previous state Yes Reduce() or loop

Question 1 of 5

You have a numeric vector x and want to compute \( \sqrt{x_i} \) for every element. Which approach is preferred in R?

Question 2 of 5

Why is vectorized code typically faster than an explicit for loop in R?

Question 3 of 5

Which of the following tasks is a valid reason to use a for loop instead of vectorization?

Question 4 of 5

What is the biggest performance problem with this code?

result <- c(); for(i in 1:1e5) result <- c(result, i^2)

Question 5 of 5

Which line of R code is a vectorized replacement for this loop?

for(i in 1:n) if(x[i] > 0) y[i] <- "pos" else y[i] <- "neg"