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
}
lapply() # list apply

sapply() # apply with vector output

apply() # loop over rows or columns of a data.frame
sapply(seq(10), function(x){
  x^2
})
 [1]   1   4   9  16  25  36  49  64  81 100