Control Structures

This will help us to control the flow of the R program. It is very much similar to other type of programming language’s Control Structure. Lets look into some common ones,

  • If-else
  • For loops
  • Nested for loops
  • While Loops
  • Repeat Loops and break
  • Next

If-else

> num <- 10
> if(num <= 0){ ## Condition
+ ## do something
+ print("'num' is less than 0")
+ }else{
+ ## do something else
+ print("'num' is greater than 0")
+ }
[1] "'num' is greater than 0"
> ## Condition with ifelse (Compact way)
> ifelse(num <= 0,"'num' is less than 0","'num' is greater than 0")
[1] "'num' is greater than 0"

For loops

A for loop will help to iterate through iterable objects.

> for(i in 1:3){
+ print(i)
+ }
[1] 1
[1] 2
[1] 3
> veh <- c("car", "van", "bus") ## Create a vector with vehicles
>
> ## Iterate without index value
> for(i in veh){
+ print(i)
+ }
[1] "car"
[1] "van"
[1] "bus"
>
> ## Iterate through the vector object based on the interger vector
> for(i in 1:3){
+ print(veh[i])
+ }
[1] "car"
[1] "van"
[1] "bus"
>
> ## Generate a sequence based on length of 'veh' object
> for(i in seq(veh)){
+ print(veh[i])
+ }
[1] "car"
[1] "van"
[1] "bus"
>
> ## Curly brakets are not a must
> for(i in veh) print(i)
[1] "car"
[1] "van"
[1] "bus"

Nested Loop

> ## Create a matrix
> my_mat <- matrix(1:6, 2, 3)
>
> ## Iterate the matrix using nested loops
> for(r in seq_len(nrow(my_mat))){
+ for(c in seq_len(ncol(my_mat))){
+ print(my_mat[r, c])
+ }
+ }
[1] 1
[1] 3
[1] 5
[1] 2
[1] 4
[1] 6

While Loop

> c <- 0 ## Count 
> while(c < 3){
+ print(c) ## Iterate until it reach c=2
+ c <- c + 1
+ }
[1] 0
[1] 1
[1] 2

Repeat Loops and break

The repeat loop initiates an infinite loop. Like in other programming language if we want to stop the loop we should use break.

> c <- 1 ## Count
> repeat{
+ if(c == 3){
+ print("'c' reached to 3")
+ break ## break the infinite loop
+ }
+ print(c)
+ c <- c + 1 ## Increment
+ }
[1] 1
[1] 2
[1] "'c' reached to 3"

Next

next is used to skip an iteration of a loop.

> for(c in 1:10){
+ if(c <= 5){
+ next ## Skip the first 5 indices
+ }
+ print(c) ## Do something here
+ }
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Blog Series