01 / 21

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.

R Programming

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.

x <- c(3, 7, 1, 9, 4) 3 7 1 9 4 [1] [2] [3] [4] [5]

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.

Input 3 7 1
\( x^2 \)
Output 9 49 1 vs Loop Approach for (i in 1:length(x))
i=1: out[1]=\( 3^2 \)=9
i=2: out[2]=\( 7^2 \)=49
i=3: out[3]=\( 1^2 \)=1
Slow: one element at a time

Why Vectorize Your Code?

★ Speed
Vectorized ops run in optimized C under the hood: often 10-100x faster than R-level loops.
★ Clarity
One line of vectorized code replaces 5-10 lines of loop boilerplate, making intent obvious.
★ Safety
No off-by-one errors, no forgotten index updates: fewer bugs by design.

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.

R
x <- c(2, 4, 6) sqrt(x) # [1] 1.414 2.000 2.449

Built-in Vectorized Operations

Arithmetic + - * / ^ %% c(1,2) + c(3,4) # [1] 4 6 Element-wise Comparison > < == != >= c(3,7,2) > 4 # F T F Returns logical vector Math Functions sqrt log abs round log(c(1,10,100)) # 0.0 2.3 4.6 Applied to each element String paste nchar toupper nchar(c("hi","bye")) # [1] 2 3 Works on char vectors Logical & | ! xor !c(TRUE, FALSE) # FALSE TRUE Element-wise logic Your Functions! Vectorize() / ifelse my_fn <- function(x) x^2 + 1 Auto-vectorized if built on vec ops

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

1
Use vectorized primitives inside your function. Operators like +, *, and functions like sqrt(), ifelse() are already vectorized.
2
Replace if/else with ifelse(). The scalar if only checks one value. The vectorized ifelse(test, yes, no) works on entire vectors.
3
Avoid indexing inside loops. If you find yourself writing out[i] <-, refactor to a whole-vector operation.
4
Test with a vector. Pass a vector of 3-5 values to verify your function returns a vector of the same length.
5
Last resort: use 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.

R
celsius_to_f <- function(c_temps) { c_temps * 9 / 5 + 32 } temps <- c(0, 20, 37, 100) celsius_to_f(temps) # [1] 32.0 68.0 98.6 212.0

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.

R
classify <- function(scores, threshold = 60) { ifelse(scores >= threshold, "Pass", "Fail") } grades <- c(85, 42, 73, 59, 91) classify(grades) # [1] "Pass" "Fail" "Pass" "Fail" "Pass"

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.

R
bmi <- function(weight_kg, height_m) { weight_kg / height_m^2 } patients <- data.frame( name = c("Alice", "Bob", "Carol"), weight = c(62, 85, 70), height = c(1.65, 1.80, 1.72) ) patients$bmi <- bmi(patients$weight, patients$height) # name weight height bmi # 1 Alice 62 1.65 22.77 # 2 Bob 85 1.80 26.23 # 3 Carol 70 1.72 23.66

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.

a 1 2 3 4 + b 10 20 Recycled to: 10 20 10 20 = 11, 22, 13, 24 ★ R warns if the longer length is not a multiple of the shorter

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()
Applies a function to each element of a vector/list. Returns a simplified vector or matrix.
lapply()
Same as sapply() but always returns a list. Safer for programming.
vapply()
Like sapply() but you specify the return type. Most robust for production code.
R
# sapply: apply nchar to each name sapply(c("cat", "elephant", "dog"), nchar) # cat elephant dog # 3 8 3

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.

Non-vectorized
label_scalar <- function(x) { if (x > 0) "positive" else if (x < 0) "negative" else "zero" } label_scalar(c(-1, 0, 5)) # Warning! Only checks first element
Vectorized version
label_vec <- Vectorize(label_scalar) label_vec(c(-1, 0, 5)) # [1] "negative" "zero" "positive"

Common Mistakes

✕ Using scalar if
Writing if (x > 0) instead of ifelse(x > 0, ...). Scalar if only tests the first element of a vector.
✕ Growing vectors in loops
Using out <- c(out, val) inside a loop. R must copy the entire vector each time: \( O(n^2) \) instead of \( O(n) \).
✕ Ignoring recycling warnings
Combining vectors of incompatible lengths without checking. R recycles silently when lengths divide evenly, causing hidden bugs.

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))

Question 2 of 5

Which function should you use for vectorized conditional logic instead of a scalar if/else?

Question 3 of 5

What is the result of c(1, 2, 3) + c(10, 20) in R?

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?

Question 5 of 5

Given:
df$new_col <- df$price * 1.08
Why does this work without a loop?