Vectorized
Functions in R
Learn to write functions that operate on entire vectors and data frames at once: the idiomatic, fast, and elegant R way.
What Is a Vector in R?
A vector is R's most fundamental data structure: an ordered collection of values that all share the same type. Almost everything in R is a vector, from a single number to a column in a data frame.
What Does Vectorized Mean?
A vectorized function takes a vector as input and returns a vector of the same length, applying the operation to every element at once: no explicit loop required.
Why Vectorize Your Code?
The Core Principle
A function \(f\) is vectorized if, given a vector \( \mathbf{x} = (x_1, x_2, \ldots, x_n) \), it returns:
In other words, the function maps over every element and returns a result of the same shape as the input. This holds for arithmetic operators, math functions, logical comparisons, and your own custom functions.
Built-in Vectorized Operations
Vectorized vs. Loop: Key Distinction
| Vectorized | Explicit Loop | |
|---|---|---|
| Syntax | x * 2 |
for (i in ...) out[i] <- x[i]*2 |
| Lines of code | 1 | 4-6 |
| Speed (\( n = 10^6 \)) | ~3 ms | ~120 ms |
| Bug risk | Low | Higher |
| Readability | Declarative | Imperative |
How to Write Vectorized Functions
+, *, and functions like sqrt(), ifelse() are already vectorized.if/else with ifelse(). The scalar if only checks one value. The vectorized ifelse(test, yes, no) works on entire vectors.out[i] <-, refactor to a whole-vector operation.Vectorize(). Wraps a non-vectorized function so it maps over vector inputs via mapply().Example 1: Celsius to Fahrenheit
Convert temperatures using the formula \( F = C \times \frac{9}{5} + 32 \). Because * and + are vectorized, the function automatically works on vectors.
Example 2: Branching with ifelse()
Classify exam scores as "Pass" or "Fail" for an entire class at once. The vectorized ifelse() checks each element of the vector independently.
Example 3: Operating on a Data Frame
Data frame columns are vectors. A vectorized function applied to a column returns a new column: no row-by-row iteration needed.
Vector Recycling: A Hidden Feature
When you combine vectors of different lengths, R silently recycles the shorter one. This is powerful but can cause subtle bugs.
The apply Family
When a function is not natively vectorized, R provides the apply family to map it over data structures without explicit loops.
sapply() but always returns a list. Safer for programming.sapply() but you specify the return type. Most robust for production code.The Vectorize() Wrapper
Sometimes you have a function that uses scalar if/else or other non-vectorized logic. Vectorize() wraps it to handle vectors automatically.
Common Mistakes
ifif (x > 0) instead of ifelse(x > 0, ...). Scalar if only tests the first element of a vector.out <- c(out, val) inside a loop. R must copy the entire vector each time: \( O(n^2) \) instead of \( O(n) \).Summary: Vectorization Toolkit
| Technique | When to Use | Example |
|---|---|---|
| Arithmetic ops | Element-wise math | x * 2 + 1 |
ifelse() |
Vectorized branching | ifelse(x > 0, x, 0) |
sapply() |
Map any function | sapply(x, my_fn) |
vapply() |
Type-safe mapping | vapply(x, fn, numeric(1)) |
Vectorize() |
Wrap scalar functions | Vectorize(my_fn) |
| Boolean indexing | Subset by condition | x[x > 0] |
Question 1 of 5
What does the following R code return?sqrt(c(4, 9, 16))
sqrt() is vectorized: it applies the square root to every element, returning \( (\sqrt{4},\; \sqrt{9},\; \sqrt{16}) = (2, 3, 4) \).Question 2 of 5
Which function should you use for vectorized conditional logic instead of a scalar if/else?
ifelse(test, yes, no) evaluates the condition for every element of a vector and returns a vector of the same length. switch() is scalar-only, which() returns indices, and filter() is for time series or dplyr rows.Question 3 of 5
What is the result of c(1, 2, 3) + c(10, 20) in R?
c(10, 20, 10), giving c(11, 22, 13). Since 3 is not a multiple of 2, R also issues a warning about partial recycling.Question 4 of 5
You have a non-vectorized function f(x) that uses if/else. What is the best way to make it work on vectors?
ifelse() or dplyr::case_when() creates a truly vectorized function that runs in optimized C. Vectorize() is a convenience wrapper that still loops internally via mapply(), so it is not a true performance fix.Question 5 of 5
Given:df$new_col <- df$price * 1.08
Why does this work without a loop?
* operator is vectorized, so df$price * 1.08 multiplies every element of the price column by 1.08 in one operation. The scalar 1.08 is recycled to match the column length.