The apply Family in R

Interactive R tutorial on sapply, lapply, apply and tapply: run a function over vectors, lists, matrix rows and groups β€” loops without loops, live in your browser.

The apply family runs a function over data β€” loops without writing loops. Edit and Run each box.

Watch: the apply family in 90 seconds

Every step below β€” sapply, lapply, apply and tapply β€” run live in RStudio, then try each one in the consoles that follow.

Download the R script  Β·  β–Ά Practice in the playground β€” or edit and run each snippet below.

sapply: one result per element

Use your own function

Define an anonymous function right inside the call:

lapply returns a list

Same idea as sapply, but the result is always a list:

apply: matrix rows (1) or columns (2)

The second argument is the margin β€” 1 for rows, 2 for columns:

tapply: summarise by group

One vector summarised by the groups in another β€” a tiny group-by:

Your turn


Next: Working with text β†’ β€” base R’s string toolkit.