How to Use sapply in R: Simple Apply Function Explained
In R,
sapply applies a function to each element of a list or vector and tries to simplify the result into a vector or matrix. It is a user-friendly way to perform repetitive operations on data without writing loops.Syntax
The basic syntax of sapply is:
sapply(X, FUN, ...)
Where:
Xis a vector or list to process.FUNis the function to apply to each element ofX....are optional arguments passed toFUN.
r
sapply(X, FUN, ...)
Example
This example shows how to use sapply to square each number in a vector:
r
numbers <- 1:5 squares <- sapply(numbers, function(x) x^2) print(squares)
Output
[1] 1 4 9 16 25
Common Pitfalls
One common mistake is expecting sapply to always return a vector. If the function returns different types or lengths, the output may be a list instead. Also, using lapply returns a list always, so choose sapply when you want simplified output.
Another pitfall is forgetting that sapply applies the function element-wise, so the function should accept a single element, not the whole vector.
r
wrong <- sapply(1:3, function(x) c(x, x^2)) print(wrong) # returns a matrix, not a vector right <- lapply(1:3, function(x) c(x, x^2)) print(right) # returns a list
Output
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 4 9
[[1]]
[1] 1 1
[[2]]
[1] 2 4
[[3]]
[1] 3 9
Quick Reference
| Parameter | Description |
|---|---|
| X | Vector or list to apply function on |
| FUN | Function to apply to each element |
| ... | Additional arguments passed to FUN |
| Return | Simplified result (vector, matrix) or list if simplification fails |
Key Takeaways
Use sapply to apply a function to each element of a vector or list and get a simplified result.
The function passed to sapply should accept a single element, not the whole vector.
If output types vary, sapply may return a list instead of a vector.
Use lapply if you always want a list output without simplification.
sapply is a convenient alternative to loops for element-wise operations.