R sapply and vapply
sapply() and vapply() run a function on every item of a list or vector. sapply() tries to simplify the result, while vapply() checks each result against a template.
sapply simplifies to a vector
Each mean is a single number. sapply() joins them into one named vector.
scores <- list(a = c(10, 20), b = c(30, 40, 50))
print(sapply(scores, mean))sapply simplifies to a matrix
The function gives two named values for each item. sapply() places them in a matrix with one column per item.
scores <- list(a = c(10, 20), b = c(30, 40, 50))
print(sapply(scores, function(v) c(total = sum(v), n = length(v))))sapply stays a list
The two results have different lengths. sapply() cannot join them, so the result stays a list.
groups <- list(a = c(1, 2), b = c(1, 2, 3))
print(sapply(groups, function(x) x * 2))vapply with a template
numeric(1) says each result is one number. Each sum fits the template, so a named vector prints.
scores <- list(a = c(10, 20), b = c(30, 40, 50))
print(vapply(scores, sum, numeric(1)))Example
scores <- list(ana = c(80, 90), bo = c(60, 100))
print(sapply(scores, mean))
print(vapply(scores, mean, numeric(1)))Key points
- sapply() turns matching single results into a named vector.
- sapply() turns matching multi-value results into a matrix.
- When the results differ in length, sapply() leaves them as a list.
- vapply() takes a template such as numeric(1) for one result.
- The template states the type and length that each result must have.
- vapply() gives a named vector when every result fits the template.
In this example sapply and vapply both work out the mean of each score vector. Both calls print the same named vector, and the vapply call checks each mean against numeric(1).
Try it Yourself
Edit the code, then press Run.
Running is simulated · rdrr.io R Snippets
Exercise
What does the numeric(1) value in a vapply() call describe?