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:
- Example:
- 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:
- 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…