for (i in 1:5){
print(i)
}[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
for loopswhile loopsapply family functions as loop alternativesapply, lapply, sapply, mapply, and tapply
Full syntax:
for (iterator in sequence){
# do task
}Example:
for (i in 1:5){
print(i)
}[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Using seq():
Short form:
for (i in 1:5) print(i)[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Use for loops when you know how many iterations you need.
Syntax:
while (condition){
# do task
}Example:
a <- 1
while (a < 5){
print(a)
a <- a + 1
}[1] 1
[1] 2
[1] 3
[1] 4
The loop continues as long as the condition is TRUE.
Be careful: if the condition never becomes FALSE, the loop runs forever.
The apply family provides cleaner alternatives to explicit loops.
There are functions in R that make looping easier:
apply() – apply a function over margins of an arraylapply() – loop over a list and return a listsapply() – simplified version of lapply()mapply() – multivariate version of lapply()tapply() – apply a function over subsets of a vectorMost often used to apply a function to rows or columns of a matrix.
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
apply(m, 1, sum) # row sums[1] 22 26 30
apply(m, 2, sum) # column sums[1] 6 15 24 33
Syntax:
apply(X, MARGIN, FUN)X = matrix or arrayMARGIN = 1 (rows) or 2 (columns)FUN = function to applySimilar built-in matrix functions:
rowSums(m)[1] 22 26 30
colSums(m)[1] 6 15 24 33
rowMeans(m)[1] 5.5 6.5 7.5
colMeans(m)[1] 2 5 8 11
Note: apply() is not necessarily faster than loops, but it simplifies code.
l = long (returns list)
s = short (simplifies output)
$l1
[1] 5.5
$l2
[1] 24.5
$l3
[1] 0.2157508
sapply(list1, mean) l1 l2 l3
5.5000000 24.5000000 0.2157508
Multivariate version of lapply().
mapply(sum, 1:3, 4:6)[1] 5 7 9
Applies a function to multiple arguments element-wise.
Applies a function over subsets of a vector.
Useful for grouped summaries.