R Medium · Lesson 1 · On the house

vapply and mapply

Type-safe apply, SIMPLIFY, mapply recycling. Lesson 1 is free — on the house.

Lessons · R Medium · Lesson 1 of 10 · On the house

vapply and mapply

Type-safe apply, SIMPLIFY, mapply recycling.

Illustration for R
Lesson 1 is on the house.

vapply(X, FUN, FUN.VALUE) is the type-safe apply: you declare the shape each call must return. Example: vapply(lst, length, integer(1)) yields an integer vector. If FUN returns the wrong length or type, vapply errors — unlike sapply, which may silently give a list.

FUN.VALUE is a template: numeric(1), character(1), logical(1), or a longer prototype like numeric(2) when each call returns two numbers. The result is an array whose trailing dimension matches length(X).

mapply(FUN, ...) vectorizes a multi-argument function over parallel vectors (or lists). Shorter arguments recycle to the longest. mapply(sum, 1:3, 10:12) is like calling sum(1,10), sum(2,11), sum(3,12).

SIMPLIFY = TRUE (default for mapply/sapply) tries to collapse list results into a vector or matrix. Set SIMPLIFY = FALSE when you need a stable list. Prefer vapply when the return type is known — it documents intent and catches bugs early.

Misses: treating sapply as always returning an atomic vector, omitting FUN.VALUE on vapply, or expecting mapply to zip like Python without recycling when lengths differ.

vapply-mapply

nums <- list(a = 1:3, b = 10:12, c = 100)
lens <- vapply(nums, length, integer(1))
print(lens)
means <- vapply(nums, mean, numeric(1))
print(means)
xs <- 1:3
ys <- 10:12
print(mapply(function(x, y) x + y, xs, ys))
print(mapply(paste0, c("a", "b"), 1:2, SIMPLIFY = TRUE))
Match this when you type.

Quiz

What does vapply require that sapply does not?

Quiz

What happens if FUN returns the wrong length to vapply?

Quiz

What does mapply(FUN, xs, ys) do?

Quiz

When should you prefer vapply over sapply?

Check

Match the still for: vapply and mapply.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.