Saturday, November 21, 2020

R if Statement

 The if statement consists of the Boolean expressions followed by one or more statements. The if statement is the simplest decision-making statement which helps us to take a decision on the basis of the condition.

The if statement is a conditional programming statement which performs the function and displays the information if it is proved true.

The block of code inside the if statement will be executed only when the boolean expression evaluates to be true. If the statement evaluates false, then the code which is mentioned after the condition will run.


The syntax of if statement in R is as follows:

  1. if(boolean_expression) {  
  2.    // If the boolean expression is true, then statement(s) will be executed.   
  3. }  

Flow Chart

R If Statement

Let see some examples to understand how if statements work and perform a certain task in R.

Example 1

  1. x <-24L  
  2. y <- "shubham"  
  3. if(is.integer(x))  
  4. {  
  5.     print("x is an Integer")  
  6. }  

Output:

R If Statement

Example 2

  1. x <-20  
  2. y<-24  
  3. count=0  
  4. if(x<y)  
  5. {  
  6.     cat(x,"is a smaller number\n")  
  7.     count=1  
  8. }  
  9. if(count==1){  
  10.     cat("Block is successfully execute")  
  11. }  

Output:

R If Statement

Example 3

  1. x <-1  
  2. y<-24  
  3. count=0  
  4. while(x<y){  
  5.     cat(x,"is a smaller number\n")  
  6.     x=x+2  
  7.     if(x==15)  
  8.         break  
  9. }  

Output:

R If Statement

Example 4

  1. x <-24  
  2. if(x%%2==0){  
  3.     cat(x," is an even number")  
  4. }  
  5. if(x%%2!=0){  
  6.     cat(x," is an odd number")  
  7. }  

Output:

R If Statement

Example 5

  1. year  
  2. 1 = 2011  
  3. if(year1 %% 4 == 0) {  
  4.  if(year1 %% 100 == 0) {   
  5.      if(year1 %% 400 == 0) {   
  6.          cat(year,"is a leap year")   
  7.         } else {  
  8.          cat(year,"is not a leap year")   
  9.         }  
  10.     } else {  
  11.      cat(year,"is a leap year")   
  12.     }  
  13. else {  
  14.  cat(year,"is not a leap year")   
  15. }  

Output:

R If Statement

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...