Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Control Flow and Functions

The apply Family: lapply, sapply, vapply, apply and Map

Replace loops with the R apply family. Learn lapply, sapply, vapply, apply, tapply and mapply, plus Map, Filter and Reduce, and know which one returns what.

Loops work, but a lot of loops follow one pattern: take each element, do something to it, collect the results. R captures that pattern in the apply family, a set of functions that run another function over every element of a structure and gather the answers. The code is shorter, there is no index to manage, and no result container to preallocate.

The trick to the family is knowing which member to use. The names look alike, but they differ in what they loop over and what they give back.

The idea

Every member takes data and a function (the idea from Writing Functions that functions are values):

flowchart LR
    D["Data<br/>(vector, list, matrix)"] --> F["apply a function<br/>to each piece"] --> R["Collect results<br/>(list, vector, matrix)"]

Figure: the apply pattern.

Function Loops over Returns
lapply(X, f) Elements of a vector or list Always a list
sapply(X, f) Elements Simplified: vector or matrix if possible
vapply(X, f, template) Elements Vector, with a type check
apply(M, margin, f) Rows or columns of a matrix Vector, matrix or list
tapply(x, groups, f) Groups of a vector One result per group
mapply(f, x, y) / Map Several inputs in parallel Vector or list

lapply: always a list

R
nums <- list(a = 1:3, b = 4:6)

lapply(nums, sum)
#> $a
#> [1] 6
#> 
#> $b
#> [1] 15

lapply() is predictable: a list in, a list out, same length and same names. It is the safest member when you do not know what shape the results will take, for example when each call returns a data frame.

sapply: simplify the result

sapply() is lapply() plus an attempt to tidy the output into a vector (or matrix):

R
sapply(1:5, function(i) i^2)
#> [1]  1  4  9 16 25

sapply(c("apple", "kiwi"), nchar)
#> apple  kiwi 
#>     5     4 

Note that a character input produces names automatically. Anonymous function syntax makes this tidy: sapply(1:5, \(i) i^2).

sapply() can surprise you. If every result has length one it gives a vector; if all have the same longer length, a matrix; otherwise it falls back to a list. When the input is empty, sapply() returns an empty list(), not an empty vector. This unpredictability is fine at the console but risky inside functions and packages.

vapply: the safe version

vapply() asks you to declare what each call must return, as a template. R checks it and raises an error if a result does not match:

R
vapply(1:3, function(i) i * 2, numeric(1))
#> [1] 2 4 6

vapply(1:3, function(i) as.character(i), character(1))
#> [1] "1" "2" "3"

numeric(1) means "one number per call". The return type never changes unexpectedly, even for empty input, so use vapply() in code you rely on.

apply: rows and columns of a matrix

apply(X, MARGIN, FUN) works on matrices. MARGIN = 1 goes over rows, MARGIN = 2 over columns:

R
m <- matrix(1:6, nrow = 2, byrow = TRUE)
m
#>      [,1] [,2] [,3]
#> [1,]    1    2    3
#> [2,]    4    5    6

apply(m, 1, sum)
#> [1]  6 15

apply(m, 2, max)
#> [1] 4 5 6

For plain sums and means, the dedicated rowSums(), colMeans() and friends from Matrices and Arrays are faster.

tapply: by group

tapply(values, groups, FUN) splits a vector by a grouping vector and applies the function to each group. With the built-in mtcars data, the average fuel economy by number of cylinders:

R
tapply(mtcars$mpg, mtcars$cyl, mean)
#>        4        6        8 
#> 26.66364 19.74286 15.10000 

The names are the group labels. In dplyr Basics you will meet group_by() and summarise(), which do the same job with a table-shaped result and are usually preferred for data frames.

mapply and Map: several inputs together

When you need to walk through two or more vectors in step, use mapply():

R
mapply(function(x, y) x + y, 1:3, 4:6)
#> [1] 5 7 9

mapply(rep, 1:3, 3:1)
#> [[1]]
#> [1] 1 1 1
#> 
#> [[2]]
#> [1] 2 2
#> 
#> [[3]]
#> [1] 3

The second example calls rep(1, 3), rep(2, 2), rep(3, 1). Results of different lengths cannot be simplified, so a list comes back. Map(f, x, y) is the same with a list always returned.

Filter, Reduce and Position

A few more functional helpers are worth knowing:

R
Filter(function(x) x %% 2 == 0, 1:6)
#> [1] 2 4 6

Reduce(`+`, 1:4)
#> [1] 10

Reduce(`+`, 1:4, accumulate = TRUE)
#> [1]  1  3  6 10
  • Filter() keeps elements for which the function returns TRUE.
  • Reduce() combines elements one by one into a single value (here the sum), and accumulate = TRUE keeps every intermediate result.

Apply functions versus loops

An apply call and a loop with a preallocated result do the same work at similar speed. The advantages of apply are readability and fewer bugs. For simple arithmetic neither is needed: x^2 beats sapply(x, \(i) i^2) every time. The same idea in Python is a list comprehension, shown here as a runnable comparison:

Python Comparison: map-style code in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The tidyverse offers the purrr package (map(), map_dbl(), map_chr()) as a more consistent alternative to the apply family. The ideas are identical; only the names differ.

Choosing quickly

Which apply function?

lapply List in, list out
sapply Tidy vector if possible
vapply Tidy, with type check
apply Rows or columns

When unsure, start with lapply.

1 / 2

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does lapply() always return?

    lapply is consistent. Use sapply or vapply for simplified output.
  2. 2. Which function runs a function over each row of a matrix?

    MARGIN = 1 is rows, MARGIN = 2 is columns.
  3. 3. Why is vapply() safer than sapply() in your own functions?

    The template such as numeric(1) makes mismatches an error and keeps empty input typed.
  4. 4. What does Reduce(`+`, 1:4, accumulate = TRUE) return?

    accumulate = TRUE returns all running totals.

Summary

  • The apply family runs a function over each piece of your data and collects the results.
  • lapply() returns a list, sapply() simplifies, vapply() simplifies safely.
  • apply() handles matrix rows and columns, tapply() groups a vector, mapply()/Map() iterate several inputs together.
  • Filter() and Reduce() select and combine.
  • For plain arithmetic, vectorized operators beat all of them.

Next: Errors, Warnings and Debugging