This lesson is being piloted (Beta version)

Looping on the command line

Overview

Teaching: 10 min
Exercises: 0 min
Questions
  • How to apply function over the list, matrix?

Objectives
  • Learn apply, sapply, lapply function

There are functions in R that make looping easier:

apply

str(apply)
m <- matrix(1:12,3,4)
print(m)
apply(m,1,sum)
apply(m,2,sum)

Similar functions for matrix:

rowSums(m)
colSums(m)
rowMeans(m)
colMeans(m)

lapply & sapply

l: long s: short lapply & sapply applies the FUN to each element of a list

list1 <- list(l1 = seq(1,10),l2=20:29,l3=rnorm(4))
lapply(list1,mean)
sapply(list1,mean)

Key Points

  • apply function