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.
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.
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.
Why Vectorization Matters
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.
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.
Loop vs Vectorized
Side by side: adding 10 to every element of a vector.
Categories of Vectorized Operations
Applied element-wise to one or two vectors.
Returns a logical vector of TRUE/FALSE.
Element-wise AND, OR, NOT on logical vectors.
Apply to every element automatically.
How to Apply Vectorization
Example 1: Squaring a Vector
Given \( x = \text{c}(2, 5, 8, 3) \), compute \( x^2 \) for each element.
Example 2: Logical Filtering
Find all scores above 70 in a grades vector.
Example 3: Two-Vector Operations
Compute the total price for each item: \( \text{price} \times \text{quantity} \).
Vectorized Conditional: ifelse()
R's ifelse() function is the vectorized version of if/else. It tests every element and returns a value for each.
Aggregate Functions
Some vectorized functions take a vector and return a single summary value.
sum(c(1,2,3)) → 6
mean(c(4,8,12)) → 8
max(c(5,2,9)) → 9
cumsum(c(1,2,3)) → c(1, 3, 6)
Common Mistakes
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?