4 Loops and flow control

4.1 Loops with for

  • In R the for loop is used perform a task for each element in a set. The syntax is:
> for (var in num1:num2){
>   instruction1
>   instruction2
>   ...
> }
  • Example:
> y <- sample(1:5)
> z <- c()
> for (i in 1:5){
+   z[i] <- y[i]^2
+ }
> z
## [1]  9 25 16  4  1
  • Another example:
> M <- matrix(sample(1:12),4,3)
> M
##      [,1] [,2] [,3]
## [1,]   11    9   12
## [2,]    7    2    4
## [3,]    6    5    3
## [4,]    8    1   10
> 
> for (i in 1:4){
+   for (j in 1:3){
+     print(paste("M(",i,",",j,") =", M[i,j]))
+   }
+ }
## [1] "M( 1 , 1 ) = 11"
## [1] "M( 1 , 2 ) = 9"
## [1] "M( 1 , 3 ) = 12"
## [1] "M( 2 , 1 ) = 7"
## [1] "M( 2 , 2 ) = 2"
## [1] "M( 2 , 3 ) = 4"
## [1] "M( 3 , 1 ) = 6"
## [1] "M( 3 , 2 ) = 5"
## [1] "M( 3 , 3 ) = 3"
## [1] "M( 4 , 1 ) = 8"
## [1] "M( 4 , 2 ) = 1"
## [1] "M( 4 , 3 ) = 10"

4.2 Flow control: if and if else statements

The syntax is:

if (condition){
  expression_if_true else expression_if_false
}
  • Example:
> (x <- sample(1:3))
## [1] 2 1 3
> 
> if (x[1] < x[2] & x[2] < x[3]) print("Ordered vector") else
+     print(sort(x))
## [1] 1 2 3
> (x <- 1:3)
## [1] 1 2 3
> 
> if (x[1] < x[2] & x[2] < x[3]) print("Ordered vector") else
+     print(sort(x))
## [1] "Ordered vector"
  • Another example:
> for(i in 1:3){
+   if (i == 2) print("The index is 2") else
+     print("The index is not 2")
+ }
## [1] "The index is not 2"
## [1] "The index is 2"
## [1] "The index is not 2"
  • A shorter version…
> ifelse(condition, expression_if_true, expression_if_false)
> (x <- rnorm(2,0,1))
## [1] 0.9001 2.1645
> ifelse(x[1] < x[2], "True", "False")
## [1] "True"

4.3 While loop example

  • The while loop: while(cond) expr
> x <- 1
> while (x < 5) {
+   x <- x+1
+   print(x)
+ }
## [1] 2
## [1] 3
## [1] 4
## [1] 5
> x <- 1
> while (x < 5) {
+   print(x)
+   x <- x+1
+ }
## [1] 1
## [1] 2
## [1] 3
## [1] 4