for-loops

What is a loop?

  • repetition of the same tasks
  • e.g. same processing steps for multiple datasets
  • reduces code redundancies
    • less work
    • clearer workflow
    • errors easier to fix

for-loop syntax

  • do something for() every element of e.g. a vector
  • the iterator (i) can be used directly
  • or as an index for something else
# using `i` directly
x <- seq(10)

for(i in x){
  print(2^i)
}
[1] 2
[1] 4
[1] 8
[1] 16
[1] 32
[1] 64
[1] 128
[1] 256
[1] 512
[1] 1024
x <- 2:20

# using `i` as an index
for(i in 1:length(x)){
  print(x[i]^2)
}
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
[1] 49
[1] 64
[1] 81
[1] 100
[1] 121
[1] 144
[1] 169
[1] 196
[1] 225
[1] 256
[1] 289
[1] 324
[1] 361
[1] 400
# using `i` as an index
for(i in c(2, 4, 11, 7)){
  print(x[i]^2)
}
[1] 9
[1] 25
[1] 144
[1] 64
NA?

Why is there an NA output in the second example?

x <- 1:10
for(i in x){
  result <- x[i]^2
}

result
[1] 100
result

Why is the result 100? What did you expect?

Storing results of a for loop

If you want to save the result of the loop, you have to assign the output to e.g. element of a vector.

x <- 1:10
result <- c()

for(i in x){
  result[i] <- x[i]^2
}

result
 [1]   1   4   9  16  25  36  49  64  81 100
Task
  • Create a vector with 10 random numbers.
  • Create a loop that does the following:
    • multiply the number with 2 and print the result
    • divide the number by 3 and save the result