Part14 Repetitive execution
Loops are used to repeat a specific block of code.
Structure of the for loop:
3 main elements: * i is the loop variable: it is updated at each iteration. * vector_expression: value attributed to i at each iteration (the number of iterations is the length of vector_expression). * action_command: what is to be done at each iteration.
Note the usage of curly brakets {} to start and end the loop!
- Example:
## [1] 4
## [1] 6
## [1] 8
## [1] 10
- Example of a for loop that iterates over a character vector:
# Character vector
myfruits <- c("apple", "pear", "grape")
# For loop that prints the current element and its number of characters
for(j in myfruits){
print(j)
print(nchar(j))
}
## [1] "apple"
## [1] 5
## [1] "pear"
## [1] 4
## [1] "grape"
## [1] 5
- Example of a for loop that iterates over each row of a matrix, and prints the minimum value of that row :
# Matrix
mymat <- matrix(rnorm(800),
nrow=50)
# For loop over mymat rows
for(i in 1:nrow(mymat)){
print(i)
print(min(mymat[i,]))
}
## [1] 1
## [1] -1.302245
## [1] 2
## [1] -1.676981
## [1] 3
## [1] -1.196015
## [1] 4
## [1] -2.806083
## [1] 5
## [1] -2.369012
## [1] 6
## [1] -2.412379
## [1] 7
## [1] -2.695529
## [1] 8
## [1] -3.101285
## [1] 9
## [1] -2.001403
## [1] 10
## [1] -1.775279
## [1] 11
## [1] -1.893496
## [1] 12
## [1] -2.349828
## [1] 13
## [1] -1.619585
## [1] 14
## [1] -1.066003
## [1] 15
## [1] -1.497021
## [1] 16
## [1] -1.400743
## [1] 17
## [1] -2.874942
## [1] 18
## [1] -2.184579
## [1] 19
## [1] -1.504274
## [1] 20
## [1] -2.172213
## [1] 21
## [1] -1.338849
## [1] 22
## [1] -1.376689
## [1] 23
## [1] -1.307128
## [1] 24
## [1] -1.438287
## [1] 25
## [1] -2.108979
## [1] 26
## [1] -1.619519
## [1] 27
## [1] -1.828345
## [1] 28
## [1] -1.715963
## [1] 29
## [1] -1.982181
## [1] 30
## [1] -1.488884
## [1] 31
## [1] -2.226057
## [1] 32
## [1] -1.195805
## [1] 33
## [1] -2.657302
## [1] 34
## [1] -1.350658
## [1] 35
## [1] -1.51192
## [1] 36
## [1] -1.870979
## [1] 37
## [1] -1.390813
## [1] 38
## [1] -2.656808
## [1] 39
## [1] -1.141823
## [1] 40
## [1] -1.850249
## [1] 41
## [1] -2.103125
## [1] 42
## [1] -2.386308
## [1] 43
## [1] -2.562332
## [1] 44
## [1] -1.66199
## [1] 45
## [1] -1.542725
## [1] 46
## [1] -1.615211
## [1] 47
## [1] -0.8306144
## [1] 48
## [1] -2.067982
## [1] 49
## [1] -1.28216
## [1] 50
## [1] -1.558054