ZetCode

R apply family

last modified November 19, 2026

A loop says how to visit the elements of an object. The functions in the apply family say what should happen to each element and let R handle the visiting. They are shorter than a loop, they keep the result in a predictable shape, and they make the intent of the code easier to read. This article covers apply for matrices and arrays, lapply, sapply, and vapply for lists and vectors, mapply for several vectors at once, tapply for groups, and the related functions Map, Reduce, and Filter.

Applying over margins

apply takes a matrix or an array, a margin, and a function. The margin is the dimension that is kept: 1 means rows, 2 means columns, and 3 means layers of an array. The function is called once per slice and the results are assembled into a vector or a matrix.

apply-margins.R
m <- matrix(1:6, nrow = 2, byrow = TRUE)
print(apply(m, 1, sum))
print(apply(m, 2, mean))
print(apply(m, 1, function(row) max(row) - min(row)))

The row sums are 6 and 15, and the column means are 2.5, 3.5, and 4.5. The third call uses an anonymous function, written directly in the argument list, to compute the range of each row. apply does not make the function faster than a loop; it removes the bookkeeping around the loop and chooses the result shape automatically.

$ Rscript apply-margins.R
[1]  6 15
[1] 2.5 3.5 4.5
[1] 2 2

Applying to every element

lapply calls a function for every element of a list or vector and always returns a list of the same length. Names are preserved, so a named input produces a named result. It is the safest member of the family when the results may have different lengths or types.

apply-elements.R
scores <- list(math = c(90, 80), art = c(85, 95))
result <- lapply(scores, mean)
print(result)
print(class(result))

Each subject is a numeric vector, and mean reduces it to one number. The result is still a list with two named elements, one per subject. A list is the right container when the number of values per subject is not known in advance, because a list can hold elements of different lengths.

$ Rscript apply-elements.R
$math
[1] 85

$art
[1] 90

[1] "list"

Simplifying the result

sapply is lapply followed by an attempt to simplify the list. If every result has length one and the same type, the list becomes a vector; if every result has the same length greater than one, it becomes a matrix. If no simplification is possible, the list is returned unchanged.

apply-simplify.R
scores <- list(math = c(90, 80), art = c(85, 95))
print(sapply(scores, mean))
print(class(sapply(scores, mean)))
print(sapply(scores, range))

The means become a named numeric vector, and the two ranges become a matrix with one row per statistic. sapply is convenient at the console, but its result type depends on the data, which is dangerous inside a function that callers rely on. The next function makes the expected type explicit.

$ Rscript apply-simplify.R
math  art 
  85   90 
[1] "numeric"
     math art
[1,]   80  85
[2,]   90  95

Checking the result type

vapply takes a third argument that describes the shape and type of one result, for example numeric(1) for one number or integer(1) for one integer. If any call returns something else, vapply stops with an error instead of silently changing the result type.

apply-typed.R
scores <- list(math = c(90, 80), art = c(85, 95))
print(vapply(scores, mean, numeric(1)))
print(vapply(scores, length, integer(1)))

Both calls return named vectors, and the template documents the contract: the mean is a numeric of length one, and the length is an integer of length one. In package code vapply is preferred over sapply precisely because a surprise in the data becomes a clear error at the call site rather than a wrong result downstream.

$ Rscript apply-typed.R
math  art 
  85   90 
math  art 
   2    2 

Several vectors at once

mapply calls a function with the first element of every vector, then the second element of every vector, and so on. It is the vectorised version of a loop over several sequences. Map does the same work and always returns a list, which is why it is described as mapply with simplification turned off.

apply-multiple.R
prices <- c(100, 200, 300)
rates <- c(0.05, 0.10, 0.20)
print(mapply(function(price, rate) price * rate, prices, rates))
print(Map(function(a, b) a + b, 1:3, 4:6))

The first call pairs each price with its rate and returns 5, 20, and 60. The second pairs the two integer sequences and returns a list of three sums. Shorter inputs are recycled, so a single rate would be applied to every price. The function must accept as many arguments as there are vectors.

$ Rscript apply-multiple.R
[1]  5 20 60
[[1]]
[1] 5

[[2]]
[1] 7

[[3]]
[1] 9

Applying by group

tapply splits a vector into groups defined by a factor, applies a function to each group, and returns the results named by the levels. It is the base R way to compute one summary per category without writing a loop over the unique values.

apply-groups.R
scores <- c(90, 85, 66, 78, 92, 71)
subject <- factor(c("math", "art", "math", "art", "math", "art"))
print(tapply(scores, subject, mean))
print(tapply(scores, subject, length))

The mathematics scores average 82.67 and the art scores 78, and each group contains three values. The result is ordered by the factor levels, not by the order of the data. tapply accepts several grouping factors, which produces a table with one dimension per factor.

$ Rscript apply-groups.R
     art     math 
78.00000 82.66667 
 art math 
   3    3 

Reduce and Filter

Reduce combines the elements of a vector or list two at a time with a binary function, which turns a whole sequence into one value. Filter keeps the elements for which a predicate returns true. Both take a function as their first argument and a collection as their second.

reduce.R
print(Reduce("+", 1:5))
print(Reduce(function(a, b) a * b, 1:5))
print(Filter(function(x) x %% 2 == 0, 1:10))

The first reduction adds the numbers from one to five and returns 15; the second multiplies them and returns 120. The filter keeps the even numbers. Reduce is the fold of functional programming, and Filter is the selection that a logical index performs on a vector, expressed as a function call.

$ Rscript reduce.R
[1] 15
[1] 120
[1]  2  4  6  8 10

A complete example

The next script summarises the numeric columns of a data frame and computes a ratio for every row. The data frame is reduced to its numeric columns first, so the character name column is not passed to mean. sapply and vapply produce the same numbers, and mapply pairs two columns that must stay aligned.

report.R
students <- data.frame(
  name = c("Ada", "Grace", "Alan", "Edsger"),
  score = c(90, 85, 66, 78),
  hours = c(12, 10, 8, 11)
)
measures <- students[, c("score", "hours")]
print(sapply(measures, mean))
print(vapply(measures, mean, numeric(1)))
print(round(mapply(function(score, hours) score / hours,
                   students$score, students$hours), 2))

The average score is 79.75 and the average study time is 10.25 hours. sapply returns a named vector, and vapply returns the same values with the type checked. The last call computes points per hour for each student, pairing the two columns by position. The result is rounded for printing but keeps full precision in memory.

$ Rscript report.R
score hours 
79.75 10.25 
score hours 
79.75 10.25 
[1] 7.50 8.50 8.25 7.09

Next steps

The subsetting article explains the logical indices that Filter and the grouping functions rely on, and the missing values article shows how na.rm is passed through an apply call. The dplyr article later in the series replaces tapply with grouped summaries and the purrr article replaces lapply with typed map functions.

Source

R documentation: apply

R documentation: lapply, sapply, and vapply

R documentation: mapply and Map

R documentation: tapply

In this article we have applied functions over matrix margins with apply, over list elements with lapply, and over vectors with sapply and type-checked vapply. We paired several vectors with mapply and Map, summarised groups with tapply, and folded and filtered sequences with Reduce and Filter. The final example summarised the numeric columns of a data frame and computed a per-row ratio. The series continues with data wrangling in dplyr.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.