If statement is used for decision making in R to help out to make a decision on the basis of condition. If statement in R is a conditional programming statement that displays the information if it is proved true. The if statement consists of the Boolean expressions followed by one or more statements.
If statement is only executed when the Boolean expression to be true inside the block code. If the statement evaluates false, then the code which is mentioned after the condition will run.
In R, the syntax of the if statement is as follows:
Flow Chart of If Statement in R
Following are some examples of if statements working and performing a particular task in R.
The following example prints the message if the condition is true.
a <-5L if(is.integer(a)) { print("a is Int") }
Output:
The following example prints the message if the condition is true then it will increment the count 1. The second condition will be true if the first condition is true.
a <-42 b <-14 c=0 if(a>b) { cat(a,"is a greater number\n") c=1 } if(c==1){ cat("Block execution successful") }
Output:
The following example will check the first condition if it is true it will print the message otherwise checks the second condition.
n <-120 if(x%%2==0){ cat(n," is even") } if(n%%2!=0){ cat(n," is odd") }
Output: