01 / 21

Vectorized
Operations in R

Learn how R processes entire vectors at once instead of looping element by element: the key to writing fast, clean, and idiomatic R code.

R Programming

What Is a Vector in R?

A vector is R's most fundamental data structure: an ordered collection of elements that all share the same type. When you write \( \text{c}(3, 7, 11, 2) \), you create a numeric vector of length 4.

\( x \leftarrow \text{c}(3, 7, 11, 2) \)
3 7 11 2 [1] [2] [3] [4]

What Does Vectorized Mean?

A vectorized operation applies a function or operator to every element of a vector simultaneously, without writing an explicit loop. R delegates the iteration to optimized internal C code.

x 3 7 11 2
\( x \times 2 \)
\( \times 2 \)
\( \times 2 \)
\( \times 2 \)
\( \times 2 \)
result 6 14 22 4 All 4 multiplications happen in ONE internal call Vectorized Loop (for i in 1:4) ~1 call ~4 calls

Why Vectorization Matters

★ Speed
Internal C/Fortran loops are orders of magnitude faster than R-level for loops, especially on large data.
★ Clarity
One expressive line like \( x \times 2 \) replaces 3-5 lines of loop scaffolding, making code easier to read.
★ Fewer Bugs
No off-by-one errors, no forgotten pre-allocation. The operation is declarative: say what, not how.

The Core Principle

When an operator or function in R receives a vector, it automatically applies the operation to every element and returns a vector of the same length.

\( f( ) \)
vectorized function x [3, 7, 11, 2] result
[\( f(3), f(7), f(11), f(2) \)]
No loop needed: R handles the iteration internally

The Recycling Rule

When you combine two vectors of different lengths, R silently recycles the shorter one to match the longer one. This is how scalar operations work: the scalar is a length-1 vector that gets recycled.

x 1 2 3 4 + y 10 20 recycled y: 10 20 10 20 result 11 22 13 24
\( 1+10=11, 2+20=22, 3+10=13, 4+20=24 \)

Loop vs Vectorized

Side by side: adding 10 to every element of a vector.

✕ Loop Approach
x <- c(3, 7, 11, 2) result <- numeric(length(x)) for (i in seq_along(x)) { result[i] <- x[i] + 10 }
✓ Vectorized
x <- c(3, 7, 11, 2) result <- x + 10 # result: [13, 17, 21, 12]

Categories of Vectorized Operations

★ Arithmetic
+, -, *, /, ^, %%
Applied element-wise to one or two vectors.
★ Comparison
>, <, ==, !=, >=, <=
Returns a logical vector of TRUE/FALSE.
★ Logical
&, |, !
Element-wise AND, OR, NOT on logical vectors.
★ Math Functions
\( \sqrt{\cdot} \), \( \log(\cdot) \), \( \text{abs}() \), \( \text{round}() \), \( e^x \)
Apply to every element automatically.

How to Apply Vectorization

1
Identify the loop. Look for any for or while loop that processes one element at a time.
2
Find the operation. Isolate what happens to each element inside the loop body (e.g., multiply, compare, transform).
3
Apply to the whole vector. Replace the loop with a single expression that operates on the entire vector at once.
4
Verify with a small example. Test on a short vector to confirm the vectorized version returns the same result.

Example 1: Squaring a Vector

Given \( x = \text{c}(2, 5, 8, 3) \), compute \( x^2 \) for each element.

x 2 5 8 3
\( x^2 \)
result 4 25 64 9
x <- c(2, 5, 8, 3) result <- x^2 # [1] 4 25 64 9

Example 2: Logical Filtering

Find all scores above 70 in a grades vector.

grades <- c(85, 62, 91, 70, 55, 78) # Step 1: vectorized comparison (returns logical vector) passing <- grades > 70 # [1] TRUE FALSE TRUE FALSE FALSE TRUE # Step 2: use logical vector to subset grades[passing] # [1] 85 91 78

Example 3: Two-Vector Operations

Compute the total price for each item: \( \text{price} \times \text{quantity} \).

price <- c(4.50, 2.00, 8.75, 1.25) quantity <- c(3, 10, 1, 6) total <- price * quantity # [1] 13.50 20.00 8.75 7.50 sum(total) # [1] 49.75
price 4.50 2.00 8.75 1.25
\( \times \)
qty ... total 13.50 20.00 8.75 7.50 sum = 49.75

Vectorized Conditional: ifelse()

R's ifelse() function is the vectorized version of if/else. It tests every element and returns a value for each.

scores <- c(85, 42, 91, 67, 73) result <- ifelse(scores >= 70, "Pass", "Fail") # [1] "Pass" "Fail" "Pass" "Fail" "Pass"

Aggregate Functions

Some vectorized functions take a vector and return a single summary value.

sum()
Total of all elements:
sum(c(1,2,3)) → 6
mean()
Average value:
mean(c(4,8,12)) → 8
max() / min()
Extremes:
max(c(5,2,9)) → 9
cumsum()
Running total (returns a vector):
cumsum(c(1,2,3)) → c(1, 3, 6)

Common Mistakes

✕ Growing a vector in a loop
Using result <- c(result, new_value) inside a loop forces R to copy the entire vector each iteration. Pre-allocate or vectorize.
✕ Using if instead of ifelse
Writing if(x > 5) when x is a vector only tests the first element. Use ifelse() for element-wise conditionals.
✕ Ignoring recycling warnings
When vector lengths don't divide evenly, R warns but still recycles. This usually means your data is misaligned.

Loop vs Vectorized Summary

for Loop Vectorized
Speed Slow (R-level iteration) Fast (C-level)
Lines of Code 3-5 lines Usually 1 line
Readability Must trace loop logic Declarative intent
Bug Risk Off-by-one, pre-allocation Minimal
When to Use Complex dependencies between iterations Same operation on every element

Question 1 of 5

Given \( x \leftarrow \text{c}(4, 9, 16) \), what does \( \sqrt{x} \) return?

Question 2 of 5

What is the main advantage of vectorized operations over explicit for loops in R?

Question 3 of 5

Given \( x \leftarrow \text{c}(1, 2, 3, 4) \) and \( y \leftarrow \text{c}(10, 20) \), what does \( x + y \) return?

Question 4 of 5

You want to label each score as "Pass" or "Fail" based on whether it is \( \ge 60 \). Which approach is correct for a vector of scores?

Question 5 of 5

Which of the following is NOT an example of a vectorized operation in R?