Skip to content
R

Apply Family

Apply functions over arrays, lists, and groups with apply, lapply, sapply, tapply.

By EZ4Code Team
applyvectorization

Code

mat <- matrix(1:12, nrow = 4, byrow = TRUE)
print(mat)

# apply - over array margins
print(apply(mat, 1, sum))   # row sums
print(apply(mat, 2, mean))  # column means
print(apply(mat, 2, function(col) col^2))

# lapply - over list, returns list
lst <- list(a = 1:3, b = 4:6, c = 7:9)
print(lapply(lst, sum))
print(lapply(lst, mean))

# sapply - simplified to vector
print(sapply(lst, sum))

# vapply - typed for safety
print(vapply(lst, mean, numeric(1)))

# mapply / Map - element-wise over multiple
print(mapply(function(x, y) x + y, 1:3, 10:12))

# tapply - grouped aggregation
df <- data.frame(
  group = rep(c("A", "B"), each = 5),
  value = c(1, 2, 3, 4, 5, 10, 20, 30, 40, 50)
)
print(tapply(df$value, df$group, mean))
print(tapply(df$value, df$group, range))

# replicate - repeated random draws
print(replicate(5, mean(rnorm(10))))

Explanation

The apply family avoids explicit loops by dispatching a function over the margins of arrays or the elements of lists. lapply always returns a list, sapply tries to simplify to a vector, and vapply enforces a return type for safety. tapply computes grouped summaries, and replicate wraps repeated random draws for simulations.

More R Snippets