7  Base R Functions & Apply Family

8 Common Utilities

x <- 1:10
sum(x); mean(x); sd(x); var(x); quantile(x)
[1] 55
[1] 5.5
[1] 3.02765
[1] 9.166667
   0%   25%   50%   75%  100% 
 1.00  3.25  5.50  7.75 10.00 
seq(0, 1, by=0.1); rep(5, times=3)
 [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
[1] 5 5 5

9 Apply Family

m <- matrix(1:9, nrow=3)
apply(m, 1, mean)  # row means
[1] 4 5 6
apply(m, 2, mean)  # col means
[1] 2 5 8
lst <- list(a=1:3, b=10:12)
sapply(lst, mean)   # simplifies result
 a  b 
 2 11 
mapply(sum, 1:3, 10:12)
[1] 11 13 15

10 Subsetting Essentials

df <- data.frame(id=1:3, val=c(10,20,30))
df[1, "val"]
[1] 10
df[df$val > 10, ]
  id val
2  2  20
3  3  30

11 Exercises

  1. Use apply to get the max per column of a numeric matrix.
  2. Write a base R snippet to compute IQR for each column of mtcars.
  3. Compare lapply vs sapply in behavior on a list with mixed types.