Reading — step 1 of 5
Learn
~1 min readFunctions
for loops in R have a reputation for being slow. The apply family is the idiomatic way to repeat operations:
sapply(x, f) — apply f to each element of x, simplify to a vector:
sapply(1:5, function(n) n * 2) # 2 4 6 8 10
sapply(c("hi", "hello"), nchar) # 2 5
lapply(x, f) — same but always returns a list (no simplification):
lapply(1:3, function(n) rep(n, n))
# list(1, c(2,2), c(3,3,3))
vapply(x, f, FUN.VALUE) — like sapply but with a guaranteed return type. Safer for production code.
Map(f, x, y) — multi-arg version. Map("+", 1:3, 10:12) → list(11, 13, 15).
These feel functional because they are. R draws heavily from Lisp's roots.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…