for Loops
3.4 for loops
Imagine we have a \(10 \times 10\) matrix, containing integers from 1 to 100:
## [,1] [,2] [,3] [,4]
## [1,] 1 2 3 4
## [2,] 11 12 13 14
## [3,] 21 22 23 24
## [4,] 31 32 33 34
## [5,] 41 42 43 44
## [6,] 51 52 53 54
## [7,] 61 62 63 64
## [8,] 71 72 73 74
## [9,] 81 82 83 84
## [10,] 91 92 93 94
## [,5] [,6] [,7] [,8]
## [1,] 5 6 7 8
## [2,] 15 16 17 18
## [3,] 25 26 27 28
## [4,] 35 36 37 38
## [5,] 45 46 47 48
## [6,] 55 56 57 58
## [7,] 65 66 67 68
## [8,] 75 76 77 78
## [9,] 85 86 87 88
## [10,] 95 96 97 98
## [,9] [,10]
## [1,] 9 10
## [2,] 19 20
## [3,] 29 30
## [4,] 39 40
## [5,] 49 50
## [6,] 59 60
## [7,] 69 70
## [8,] 79 80
## [9,] 89 90
## [10,] 99 100
We want to compute the median of each row. We can copy and paste:
## [1] 5.5
## [1] 15.5
## [1] 25.5
## [1] 35.5
## [1] 95.5
However, it is not very efficient to use copy and paste if we are dealing with a large number of columns, say 50 columns. Instead, we could use a for loop:
med <- rep(NA, 10) # 1. output
for (i in 1:10) { # 2. sequence
med[i] <- median(A[i, ]) # 3. body
}
med## [1] 5.5 15.5 25.5 35.5 45.5
## [6] 55.5 65.5 75.5 85.5 95.5
A for loop consists of three components.
output: Before starting the loop, we created an empty atomic vector
medof length 10 usingrep(). At each iteration, the median of theith row is assigned as theith element of our output vector.sequence: This part shows what to loop over. Each iteration of the
forloop assignsito a different value from1:10.body: The body part is the code that does the work. At each iteration, the code inside the braces
{}is run with a different value fori. For example, the first iteration will runmed[1] <- median(A[1,]).
3.5 for loop with an if statement
Here, we will see how to to use an if statement inside a for loop. We want to create a vector length of 10, such that the ith element is 1 if the ith element of x is even, and is 2 if the ith element of x is odd.
v <- numeric(10) # output: create a zero vector length of 10
for (i in 1:10) { # sequence
if (x[i] %% 2 == 0) { # if statement
v[i] = 1 # body
} else {
v[i] = 2
}
}
v## [1] 2 1 2 1 2 1 2 1 2 1