sapply()
sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE) Returns:
vector, matrix, or list · Added in v1.0 · Updated March 13, 2026 · Base Functions iteration apply functional base
sapply() is a user-friendly version of lapply() that attempts to simplify the result into a vector or matrix when the output can be reduced to a simpler data structure.
Syntax
sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
X | vector or list | — | A vector, list, or expression to iterate over |
FUN | function | — | The function to apply to each element |
... | arguments | — | Additional arguments passed to FUN |
simplify | logical | TRUE | If TRUE, attempt to simplify the result |
USE.NAMES | logical | TRUE | If TRUE and X has names, use them as names in the output |
Examples
Basic usage
# Square each element
sapply(1:5, function(x) x^2)
# [1] 1 4 9 16 25
# Using a built-in function
sapply(c("hello", "world"), toupper)
# [1] "HELLO" "WORLD"
With names preserved
names <- c("alice", "bob", "charlie")
sapply(names, function(x) paste0(toupper(substr(x, 1, 1)), substr(x, 2, nchar(x))))
# alice bob charlie
# "Alice" "Bob" "Charlie"
Returning a matrix
# When results have length > 1, sapply creates a matrix
sapply(1:3, function(x) c(x, x^2, x^3))
# [,1] [,2] [,3]
# [1,] 1 2 3
# [2,] 1 4 9
# [3,] 1 8 27
With additional arguments
# Pass extra arguments to FUN
sapply(c(10, 20, 30), round, digits = -1)
# [1] 10 20 30
Working with lists
df_list <- list(
a = data.frame(x = 1:3, y = 4:6),
b = data.frame(x = 7:9, y = 10:12)
)
sapply(df_list, nrow)
# a b
# 3 3
sapply(df_list, function(df) sum(df$x))
# a b
# 6 24
Common Patterns
Data transformation pipeline
# Apply multiple transformations
data <- list(
c(1, 2, 3),
c(4, 5, 6),
c(7, 8, 9)
)
sapply(data, function(x) {
x <- x + 1
x <- x / mean(x)
round(x, 2)
})
# [,1] [,2] [,3]
# [1,] 0.67 0.67 0.67
# [2,] 1.33 1.33 1.33
# [3,] 2.00 2.00 2.00
Conditional processing
values <- list(a = 1:5, b = c(2, 4, 6), c = c(1, 3, 5, 7))
sapply(values, function(x) if(all(x %% 2 == 0)) "all even" else "has odd")
# a b c
# "has odd" "all even" "has odd"
Handling missing values
vec <- c(1, 2, NA, 4, NA, 6)
sapply(vec, function(x) ifelse(is.na(x), 0, x))
# [1] 1 2 0 4 0 6
How sapply Differs from lapply
| Aspect | lapply | sapply |
|---|---|---|
| Output | Always a list | Tries to simplify to vector/matrix |
| Use case | When you need list output | When you want convenient vector output |
| Safety | More predictable | Can fail silently if simplification fails |
When simplify = FALSE, sapply() behaves exactly like lapply().