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.
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:
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:
Why Does This Matter?
The Core Principle
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.
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
x + y, x * 2, x^2 all work element-wise automatically.sqrt(x), log(x), abs(x), round(x) accept entire vectors.x > 5 returns a vector of TRUE/FALSE values without a loop.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:
Decision Flowchart
How to Apply This
ifelse(), sapply(), cumsum(), etc.Example 1: Simple Arithmetic
Example 2: Conditional Logic
Task: label each score as "Pass" or "Fail" based on a threshold of 60.
Example 3: When a Loop Wins
Task: simulate a random walk where each position equals the previous position plus a random step.
Common Mistakes
c(result, newval) inside a loop copies the entire vector each iteration: \( O(n^2) \) time.for(i in 1:n) y[i] <- x[i] + 1 when y <- x + 1 does the same thing instantly.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?
x * 2, ifelse(x < 0, 0, x), and log(x).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)
c(result, newval) allocates a new, larger vector and copies all existing elements. Over \( n \) iterations this produces \( O(n^2) \) total work. The fix: pre-allocate with numeric(1e5) or, even better, vectorize: result <- (1:1e5)^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"
ifelse() is R's vectorized conditional. The regular if/else only evaluates a single logical value, and switch() is not vectorized. sapply here returns logicals, not labels.