Loops are used for repeating similar actions multiple times. for loops iterate over a set of values. The iterator (i) changes with every iteration of the loop:
for (i inc(1,2,3)) print(i)
[1] 1
[1] 2
[1] 3
To generate sequences of integers, we can use seq_len. Let’s make a function:
print_repetitions <-function(n) {for (i inseq_len(n)) { print(i) }}
print_repetitions(2)
[1] 1
[1] 2
Control structures – while loops
while loops repeat a task until a condition is no longer met.
add_until_4 <-function(x) {while(x <4) { x <- x +1print(x) }}
add_until_4(1)
[1] 2
[1] 3
[1] 4
Exercise 1 - Function for latitudinal binning
Create a function that can sort a data.frame into hemispheres. That is, we want a new column that identifies the hemisphere of each entry of the data set. As an exemplary data set, we will use the reefs data from palaeoverse here and in the next exercises.