LOADING

Type to search

Control Structures in R –> if , else , for , while , repeat , break , next , return

To Know more about the Different Corporate Training & Consulting Visit our website www.Instrovate.com Or Email : info@instrovate.com or WhatsApp / Call at +91 74289 52788

R Programming

Control Structures in R –> if , else , for , while , repeat , break , next , return

Share

Control structures in R

These allow you to control the flow of execution of a script .

It includes :

  • if , else
  • for
  • while
  • repeat
  • break
  • next
  • return

If

The if statement allows you to control if a program enters a section of code or not based on whether a given condition is TRUE or FALSE.

The structure of If is :

if(condition) {

#do something

}

We want to check a condition if “r” greater than 30 . If the condition is TRUE than print “r“. We use print() function to print “r” object.

      r  <- 19                      

      if(r > 30){

        print(r)

      }

In above program “r” stores 19 . The condition is FALSE , if statement does not work.

Output:

If we assign “r” equal to 40 .So, if condition is TRUE and print “r” object.

r<-45

Output:

If else

Sometimes when the condition in an if statement evaluates to FALSE, it would be nice to execute some code instead of the code executed when the statement evaluates to TRUE. The “else” statement effectively says that whatever code after it (whether a single line or code between brackets) is executed if the if statement is FALSE

The structure of if else statements is:

if(condition) {

#do something

} else {

#do something

}

We are checking the condition if x greater than 1 than it shows “x greater than 1” otherwise it shows “x less or equal to 1“.

We create a variable x and store 25.

x<- 25

if(x > 1){

  print(“x greater than 1”)

} else{

  print(“x less or equal to  1”)

}

Output:

We create a variable x and store 12

Random number generation

We can create random number for the normal distribution with mean equals to 0 and standard deviation equals to 1 . We use rnorm() function to create random numbers.

We create an object to store random number by using code:

x<-rnorm(1)

x

Output:

Nested if else statements

The structure of nested if else statements is :

if(condition){

#do something  

} else{

 if(condition){

    #do something  

  }else{  

#do something  

}

}

We create a random number and compare its value by using nested if else statements as:

x<-rnorm(1)

x

if(x > 1){

    print(“x greater than 1”)

} else{

    if(x>=-1){

     print(“Between -1 and 1”)

  }else{  print(“x less than -1”)

}

}

Output:

If  and else if statements

We can check multiple conditions by using if and else if conditions as:

if(condition1){

#do something

} else if(condition){

#do something

} else { #do something

}

For example :-

x<-rnorm(1)

x

if(x>1){

  print(“x greater than 1”)

} else if(x>=-1){

  print(“Between -1 and 1”)

} else{

   print(“Less than -1”)

}

Output:

We create an object “x” which stores 0 value.

     x <- 0

We are checking x is greater than 3 . If it is TRUE than y will store 10 value otherwise 0 value.

      y <- if(x >3 ){

        10

      }  else {0}

    y

while loop

while loop executes a statement repetitively until the condition is TRUE. If the condition is FALSE then while loop abrupt .

The structure of a while loop is :

while(condition){

#do something

}

The flow diagram of while loop is :

For example :

counter<-1

while(counter<12){

  print(counter)

counter<-counter+1

}

Output:

The condition FALSE when counter equals to 12 . So, while loop iterate up to 11 times.

We can also create multiple statements in single line by using “;” . The semi-colon symbol is used to write multiple statements in a single line.

      x <- 1

     while(x < 5) {x <- x+1; print(x);}

for loop

for loop is a repetition control structure that allows you to repeat a specific number of times.

The structure of a for loop is –

for(object in range){

#do something

}

The flow diagram of for loop is :

We want to print numbers from 1 to 10.

      for(i in 1:10){

        print(i)

      }

We use seq() function to create sequence from 1 to 10 separated by 2.

      for(i in seq(1,10,by=2)){

        print(i)

      }

We create an object “a” to store character vector. We want to print all the values in “a” object.

      x <- c(“a”,”b”,”c”,”d”,”e”,”f”)

            for(i in 1:4){

        print(x[i])

      }

We create an object “x” to store matrix of 2 rows and 3 columns.

      x <- matrix(1:6,2,3)

      x

I have used seq_len() function to create sequence .

We are using two for loops to print matrix. In first for loop , we apply the loop in row and in second for loop we used columns to print matrix .

      for(i in seq_len(nrow(x))){

        for(j in seq_len(ncol(x))){

          print(x[i,j])

        }

      }

Output:

I am using if statement inside for loop .

      for( i in  1:4){

        if (i == 3){

          print(“three”)

        }  

        print(i)

      }

Output:

next statement

We are using next to skip the current iteration of a loop without terminating it.

The flow chart of next statement is :

We have used if condition to skip when i equals to 2.

      for(i in 1:3){

        if(i == 2){

          next

        }  

        print(i)

      }

Output:

We want to show values starting from 20 to 100. So , we used if statement to skip values less than or equal to 20 in for loop.

      for (i in 1:100){

        if(i <= 20){

          next()

        }  

        print(i)

      }

break statement

It is used to terminate loop immediately and resumes after the next statement following the loop.

We are breaking the loop when the value of i equals to 2.

      for(i in 1:3){

        if( i==2){

          break

        }

        print(i)

      }

repeat loop

It executes the code again and again until a stop condition is met .

The structure of repeat loop is :

repeat {

#commands

if(condition){

break

                    }

         }

The flow diagram of repeat loop is :

We create a repeat loop to print values up to 5.

      x <- 1

        repeat {

        print(x)

        x = x+1

        if (x == 6){

          break

        }

      }

Output:

Leave a Comment

Your email address will not be published. Required fields are marked *