# for Loops

## 3.4for loops

Imagine we have a $$10 \times 10$$ matrix, containing integers from 1 to 100:

A <- matrix(c(1:100), nrow = 10, byrow = TRUE)
A
##       [,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:

median(A[1, ])
## [1] 5.5
median(A[2, ])
## [1] 15.5
median(A[3, ])
## [1] 25.5
median(A[4, ])
## [1] 35.5
# ...
median(A[10, ])
## [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.

1. output: Before starting the loop, we created an empty atomic vector med of length 10 using rep(). At each iteration, the median of the ith row is assigned as the ith element of our output vector.

2. sequence: This part shows what to loop over. Each iteration of the for loop assigns i to a different value from 1:10.

3. 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 for i. For example, the first iteration will run med[1] <- median(A[1,]).

## 3.5for 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