R If Statement

In the real programming world, the R If Statement is the primary decision-making statement. The If clause tests the condition first and executes the statements depending upon the result. If the test condition is true, then only the code within the if block executes.

Syntax

The syntax of the If statement in R Programming language has a simple structure.

if (Boolean_Expression)  {
 
    Statement 1;
    Statement 2;
    ………….
    ………….
    Statement n;
}

From the above code snippet, If the Boolean_Expression / test condition inside the If statement is true, then the Statement1, Statement2,……., StatementN executed. Otherwise, all those statements are skipped.

R If Statement Flow Chart

The below picture shows the flow chart behind the If Statement.

Flow Chart
  • If the test condition is true, STATEMENT1 executes, followed by STATEMENTN.
  • If the condition is False, STATEMENTN executes because it is placed outside of the if condition block, and it has nothing to do with the condition result. Let us see one example to understand better.

R If Statement Example

This program allows the user to enter any positive integer, and it checks whether the user-specified number is Positive or Not using it.

number <- as.integer(readline(prompt="Please Enter any integer Value: "))

if (number > 1) {
  print("You have entered POSITIVE Number")
}

NOTE: If statement in this Programming does not require the curly brackets to hold a single line. But, It is always good practice to use curly brackets.

As you can see that we entered 25 as a number. This if statement program checks whether 25 is greater than 1 or not. We all know that it is True; that’s why the program is printing the text inside the print().

R If Statement 1

Let us change the number value to check what happens if the Boolean expression fails? (number < 1).

Change the Value 2

It prints nothing because -12 is less than 1, and we don’t have anything to print after the if statement block. I hope you are confused. Let us see one more example.

Example 2

This program for R if statement enables the user to enter any positive integer and check whether the number is a positive integer or Not.

number <- as.integer(readline(prompt="Please Enter any integer Value: "))

if (number > 1) {
  print("You have entered POSITIVE Number")
} 
print("This is not the Message coming from inside")
print("This Message is from Outside")

You can observe the output below. It printed all the print lines because 14 is greater than 1.

R If Statement 3

Let’s try the negative values to fail the condition in If statement deliberately.

Example 4

Here, the Boolean expression inside the If statement failed (number > 1). That’s why it prints nothing from the If block. However, it printed the code that is outside the If block.