7  Loops

7.1 Objectives

  • Write and understand for loops
  • Write and understand while loops
  • Use apply family functions as loop alternatives
  • Apply functions over lists and matrices
  • Understand apply, lapply, sapply, mapply, and tapply

7.2 For Loops

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():

for (i in seq(1, 5)){
  print(letters[i])
}
[1] "a"
[1] "b"
[1] "c"
[1] "d"
[1] "e"

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.

7.3 While Loops

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.

7.4 Apply Functions

The apply family provides cleaner alternatives to explicit loops.

There are functions in R that make looping easier:

7.4.1 apply()

Most often used to apply a function to rows or columns of a matrix.

m <- matrix(1:12, 3, 4)
print(m)
     [,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 array
  • MARGIN = 1 (rows) or 2 (columns)
  • FUN = function to apply

Similar built-in matrix functions:

[1] 22 26 30
[1]  6 15 24 33
[1] 5.5 6.5 7.5
[1]  2  5  8 11

Note: apply() is not necessarily faster than loops, but it simplifies code.

7.4.2 lapply() and sapply()

l = long (returns list)
s = short (simplifies output)

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

lapply(list1, mean)
$l1
[1] 5.5

$l2
[1] 24.5

$l3
[1] 0.2157508
sapply(list1, mean)
        l1         l2         l3 
 5.5000000 24.5000000  0.2157508 
  • lapply() always returns a list
  • sapply() tries to simplify the result (vector or matrix)

7.4.3 mapply()

Multivariate version of lapply().

mapply(sum, 1:3, 4:6)
[1] 5 7 9

Applies a function to multiple arguments element-wise.

7.4.4 tapply()

Applies a function over subsets of a vector.

x <- 1:10
group <- rep(c("A", "B"), each = 5)

tapply(x, group, mean)
A B 
3 8 

Useful for grouped summaries.

7.5 Key Points

  • Use for and while for explicit iteration
  • Use apply family functions for cleaner, more readable code
  • lapply() returns lists
  • sapply() simplifies output
  • apply() works well on matrices