lapply()

lapply(X, FUN, ...)
Returns: list · Updated March 13, 2026 · Base Functions
iteration list base functional-programming

lapply() applies a function to every element of a list or vector and returns the results as a list. It is one of the most fundamental functions in R for iteration, forming the foundation for many other apply functions. Unlike sapply() which attempts to simplify the output, lapply() always returns a list, making it predictable and reliable for downstream operations.

Syntax

lapply(X, FUN, ...)

Parameters

ParameterTypeDefaultDescription
Xlist or vectorAn atomic object or list to iterate over
FUNfunctionThe function to apply to each element
...anyAdditional arguments passed to FUN

Examples

Basic usage with a list

x <- list(a = 1:3, b = 4:6, c = 7:9)
result <- lapply(x, sum)
print(result)
# $a
# [1] 6
# $b
# [1] 15
# $c
# [1] 24

Using additional arguments

x <- list(1, 2, 3, 4, 5)
result <- lapply(x, function(elem, mult) elem * mult, mult = 10)
print(result)
# [[1]]
# [1] 10
# [[2]]
# [1] 20
# [[3]]
# [1] 30
# [[4]]
# [1] 40
# [[5]]
# [1] 50

Working with data frame columns

df <- data.frame(
  a = c(1, 2, 3),
  b = c(4, 5, 6),
  c = c(7, 8, 9)
)
result <- lapply(df, mean)
print(result)
# $a
# [1] 2
# $b
# [1] 5
# $c
# [1] 8

Common Patterns

Combining with unlist for vector output: When you need a vector instead of a list, chain unlist() or use sapply() directly.

x <- list(1, 2, 3)
# Get numeric vector instead of list
vec <- unlist(lapply(x, function(i) i^2))
print(vec)
# [1] 1 4 9

Using lapply with anonymous functions: Define functions inline for quick operations without naming them.

strings <- list("hello", "world", "r")
upper <- lapply(strings, toupper)
print(upper)
# [[1]]
# [1] "HELLO"
# [[2]]
# [1] "WORLD"
# [[3]]
# [1] "R"

See Also