Skip to main content
v2026.11,986 entries · CC-BY 4.0

Apply Function in R: apply, lapply, sapply, vapply, tapply, mapply

Which apply function in R to use: input and return type of apply, lapply, sapply, vapply, tapply and mapply, with examples from the R manual.

Written and maintained by CASRAI Editorial Board

Published

On this page

The apply functions in R (apply, lapply, sapply, vapply, tapply and mapply) run one function over the pieces of an object and collect the results, so you can replace a hand-written loop with a single call. Which one to use depends on two things: what you are looping over (a matrix, a list or vector, or groups of values) and what shape of result you need back. The table below answers that first; the sections after it give the exact signatures and the return-type rules that cause most surprises. Everything here is taken from the R reference manual pages listed under Sources.

What the apply functions are used for in research

Analysts use the apply family to compute a summary per column or row of a matrix, a statistic per element of a list (for example one summary per dataset), a statistic per group (a mean per treatment arm), or to call a function on several argument sets in step. They are part of base R, so they run in any R analysis script without loading a package. If you are deciding between this family and an explicit loop, see for looping in R; for the tidyverse equivalent, see map in R.

Apply functions in R: which one do you need?

Function Loops over Returns
apply Rows or columns of an array or matrix (set by MARGIN) A vector, an array or a list, depending on what FUN returns
lapply Each element of a vector or list Always a list
sapply Each element of a vector or list A vector or matrix when every result has the same length, otherwise a list
vapply Each element of a vector or list A vector or matrix, with length and type checked against FUN.VALUE
tapply A vector split into groups by one or more factors (INDEX) An array with one cell per group (or combination of groups)
mapply Several vectors or lists at once, element by element A simplified vector or matrix, or a list when SIMPLIFY = FALSE or results cannot be simplified

Install or access

There is nothing to install beyond R itself: apply, lapply, sapply, vapply, tapply and mapply are documented in the base package of the R manual, so they are available as soon as R starts. Open the built-in help for any of them with ?apply, ?lapply, ?tapply or ?mapply.

Step-by-step: using each apply function

1. apply(): rows or columns of a matrix

The signature is apply(X, MARGIN, FUN, ..., simplify = TRUE). X is an array, including a matrix. MARGIN picks what to loop over: 1 for rows, 2 for columns, c(1, 2) for individual cells. Operators such as + or %*% must be quoted or backquoted when passed as FUN.

m <- matrix(1:6, nrow = 2)
apply(m, 1, sum)     # row sums: 9 12
apply(m, 2, range)   # a 2 x 3 matrix: min and max of each column

2. lapply(): every element of a list or vector, result is a list

The signature is lapply(X, FUN, ...). X is a vector (atomic or list) or an expression; other objects are coerced with as.list. Extra arguments after FUN are passed on to it.

x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE, FALSE, FALSE, TRUE))
lapply(x, mean)
lapply(x, quantile, probs = 1:3/4)

3. sapply() and vapply(): the same loop, simplified

The signatures are sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE) and vapply(X, FUN, FUN.VALUE, ..., USE.NAMES = TRUE). With sapply, if every call returns a value of the same positive length, you get a vector (length 1) or a matrix with one column per element of X (length greater than 1). vapply always simplifies and requires you to say in FUN.VALUE what each call must return.

sapply(x, quantile)   # a matrix: one column per element of x
vapply(x, function(v) mean(v), numeric(1))   # a numeric vector, type-checked

4. tapply(): a function applied per group

The signature is tapply(X, INDEX, FUN = NULL, ..., default = NA, simplify = TRUE). INDEX is a list of one or more factors, each the same length as X; non-factors are coerced to factors. Extra arguments in ... are not split by group.

tapply(presidents, cycle(presidents), mean, na.rm = TRUE)

5. mapply(): several inputs in step

The signature is mapply(FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE). Arguments in ... are recycled to a common length, and the result is zero-length if any argument has length zero. Constant arguments go in MoreArgs as a list.

mapply(rep, 1:4, 4:1)                          # a list: 1 1 1 1, 2 2 2, 3 3, 4
mapply(rep, times = 1:4, MoreArgs = list(x = 42))

Output and how to read it

The shape of the result is the part most worth checking, because it changes with the data.

  • apply(): if each call to FUN returns a vector of length n greater than 1, the result is an array of dimension c(n, dim(X)[MARGIN]). If n is 1 the result is a vector when MARGIN has length 1. If the lengths differ, or simplify = FALSE, the result is a list. The result is coerced by as.vector, so factors become character.
  • lapply(): always a list, with one element per element of X.
  • sapply(): a list if simplify = FALSE or if the returns differ in length; an empty list if X has length zero.
  • tapply(): an array with one cell per group; groups with no data are NA unless you set default. If FUN does not return a single value, the result is a list-mode array and empty cells are NULL.

Troubleshooting

sapply() returned a list when I expected a vector

This happens when the calls return results of different lengths, or when X is empty (then you get an empty list, not an empty vector). Because the return type depends on the data, a script can work on one dataset and return a different type on the next. Switch to vapply and declare the expected value, for example numeric(1): it checks each result for length and type and stops with an error instead of silently changing shape. Promotion is allowed (logical to integer to double to complex) but demotion is not.

tapply() gives NA for some groups

A factor level with no observations produces NA. Pass default = 0 (as in the manual example tapply(1:n, fac, sum, default = 0)) when a sum over an empty group should be zero.

Operators as FUN in apply()

Pass operators such as + or %*% in quotes or backquotes, as the manual requires.

To build a new column from existing ones, see the mutate function in R; to understand the lists that lapply returns and consumes, see lists in R.

Free alternatives

Option When it fits
Base R for loop Explicit control over each step; see for looping in R
purrr map functions The tidyverse counterpart for looping over vectors and lists; see map in R

FAQ

What is the apply function in R?

apply() runs a function over the rows or columns of a matrix or array, selected by MARGIN (1 for rows, 2 for columns). The wider family (lapply, sapply, vapply, tapply, mapply) does the same job for lists, vectors, groups and parallel inputs.

What is the difference between lapply and sapply?

lapply always returns a list. sapply loops the same way and then simplifies the result to a vector or matrix when every result has the same positive length; otherwise it returns a list.

When should I use vapply instead of sapply?

Use vapply when the output type must be predictable, for instance inside a reusable function, because it checks every result against FUN.VALUE.

Sources

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Apply Function in R: apply, lapply, sapply, vapply, tapply, mapply

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →