Vectorization vs Loops
Vectorization is the practice of applying an operation to an entire vector at once instead of looping element by element, producing shorter, faster, and more idiomatic R code.
Learn Vectorization vs Loops in our free R course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free R course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
You'll see why vectorized operations beat for-loops in R, how recycling lets vectors of different lengths combine, how ifelse(), pmax/pmin, and rowSums/colMeans replace loops, and when a plain loop is still the right call.
What You'll Learn in This Lesson
1️⃣ The Same Job: Loop vs Vectorized
Here is the exact same task — add 20% to every price — written both ways. The loop is correct but verbose and, on large data, noticeably slower. The vectorized version is one line and runs the repetition in fast compiled code.
Both print the same result. The difference is clarity and speed: the vectorized form is what experienced R users write by default.
2️⃣ Recycling: How Lengths Combine
Vectorization relies on recycling : when two vectors differ in length, R repeats the shorter to match the longer. A plain number is just a length-1 vector, which is why x + 1 adds 1 to everything. If the longer length isn't a clean multiple of the shorter, R still computes but warns you.
3️⃣ Vectorized Branching & Reductions
ifelse() applies a condition across a whole vector and returns a same-length result — the vectorized replacement for an if/else loop. pmax() and pmin() do parallel (element-wise) max/min across two vectors.
For tabular data, rowSums() , colSums() , rowMeans() , and colMeans() reduce a whole matrix in one vectorized call — vastly faster than nested loops.
Your turn. Fill in the ___ blanks, run it, and compare with the expected output.
The constraint is the point: solve every step with vectorized functions and no for-loop . If you find yourself reaching for a loop, ask which built-in does the same job in one line.
📋 Quick Reference — Vectorization
Practice quiz
What does the vectorized expression prices * 1.2 do?
- Multiplies every element by 1.2 at once
- Multiplies only the first element
- Returns a single number
- Errors on vectors
Answer: Multiplies every element by 1.2 at once. Vectorized arithmetic applies the operation to every element.
Why are vectorized operations usually faster than R for-loops?
- They skip elements
- The repetition runs in compiled C, not the R interpreter
- They use less memory only
- They run in parallel threads
Answer: The repetition runs in compiled C, not the R interpreter. Vectorized functions push the loop down into optimised C code.
What is recycling in R?
- Garbage collection
- Reusing variable names
- Repeating the shorter vector to match the longer one
- Caching results
Answer: Repeating the shorter vector to match the longer one. When lengths differ, R repeats the shorter vector element-wise.
What does c(1, 2, 3) + c(10, 20) produce?
- An error that stops execution
- c(11, 22)
- c(11, 22, 33)
- c(11, 22, 13) with a warning
Answer: c(11, 22, 13) with a warning. R recycles (1+10, 2+20, 3+10) and warns because 3 is not a multiple of 2.
What does ifelse(temps > 20, "warm", "cool") return?
- A same-length vector of "warm"/"cool"
- A single string
- Only the first result
- TRUE or FALSE
Answer: A same-length vector of "warm"/"cool". ifelse() is vectorized and returns a vector the same length as the test.
How does a plain if () differ from ifelse()?
- if() is vectorized
- if() takes one TRUE/FALSE and uses only the first element of a vector
- They are identical
- ifelse() only works on numbers
Answer: if() takes one TRUE/FALSE and uses only the first element of a vector. if() is for control flow; ifelse() transforms a whole vector.
What does pmax(c(1, 8, 3), c(5, 2, 9)) return?
- 9 (the overall max)
- c(1, 2, 3)
- c(5, 8, 9)
- A single value
Answer: c(5, 8, 9). pmax() takes the parallel (element-wise) maximum across vectors.
How is pmax() different from max()?
- pmax() sorts
- They are the same
- max() is vectorized; pmax() is not
- max() returns one number; pmax() returns an element-wise vector
Answer: max() returns one number; pmax() returns an element-wise vector. max() reduces to one value; pmax() compares element by element.
What does rowSums(m) compute for a matrix m?
- The grand total
- The sum across each row
- The sum down each column
- The matrix mean
Answer: The sum across each row. rowSums() sums across each row in one vectorized call.
When you must keep a for-loop, what avoids the classic R slowdown?
- Use 1:length(x)
- Grow the result with c() each iteration
- Pre-allocate the output (e.g. out <- numeric(n))
- Disable warnings
Answer: Pre-allocate the output (e.g. out <- numeric(n)). Pre-allocating avoids repeatedly copying a growing vector.