R Code Flow


Line most programming languages, R provides code flow support using if/else blocks and for/while loops. No developer would need a detailed explanation about these. The below code snippets give an overview of how it is used in R code.

if / else / else if


output <- 'blank'
number <- 10

if(number > 10){
    report <- "Greater than 10"
}else if (number < 10){
    report <- "Less than 10"
}else{
    report <- 'Equal to 10'
}
print(report)

[1] Equal to 10

for loops


We have versatile for loops in R. It provides ways of looping through the various data structures like vectors, lists, matrix, arrays.

vec <- c(1,3,4,6,9)
for (v in vec) {
    print(v)
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

You can do the same with other data structures as well. Also the collection can be generated dynamically in the command:

for ( i in 1:10 ){
    print (i)
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

While Loops


While loops provide a more generic and more powerful mechanism to loop. The While loops in R are quite similar to most other languages:

> x <- 0
> while(x < 10){
+   cat('Value of x: ',x)
+   print("X is still less than 10")
+   # add one to x
+   x <- x+1
+ }
Value of x:  0[1] "X is still less than 10"
Value of x:  1[1] "X is still less than 10"
Value of x:  2[1] "X is still less than 10"
Value of x:  3[1] "X is still less than 10"
Value of x:  4[1] "X is still less than 10"
Value of x:  5[1] "X is still less than 10"
Value of x:  6[1] "X is still less than 10"
Value of x:  7[1] "X is still less than 10"
Value of x:  8[1] "X is still less than 10"
Value of x:  9[1] "X is still less than 10"
>

While loops also provide for break and next if you want to cut short through the loop at any point.