lapply-loops

R has some more specific loop types that work very well with vectors and lists. They are called lapply loops in R and make use of functions that are applied over the element of a vector or list.

The syntax of the lapply loop can be a bit confusing at first as it is the other way around as the for loop. The biggest difference is, that lapply returns a list of values for every iteration step. So the output of the loop can be assigned directly to a variable.

result <- lapply(i, FUN)

# compared to:
result <- c()
for(i in x){
  result[i] <- FUN
}

There are multiple forms of apply loops. lapply and sapply only differ in their output format. apply is used for data.frames.

lapply() # list apply

sapply() # apply with vector output

apply() # loop over rows or columns of a data.frame
lapply(seq(10), function(x){
  x^2
})
[[1]]
[1] 1

[[2]]
[1] 4

[[3]]
[1] 9

[[4]]
[1] 16

[[5]]
[1] 25

[[6]]
[1] 36

[[7]]
[1] 49

[[8]]
[1] 64

[[9]]
[1] 81

[[10]]
[1] 100
sapply(seq(10), function(x){
  x^2
})
 [1]   1   4   9  16  25  36  49  64  81 100