R If Statement

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

R If Statement 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 skipped.

R If Statement Flow Chart

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

R Programming If Statement Flow Chart
  • If the test condition is true, STATEMENT1 executed, followed by STATEMENTN.
  • If the condition is False, STATEMENTN executed because it 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

The R if statement 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 R 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 R 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).

R If Statement 2

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

If Statement example 2

This program for R if statement enables the user to enter any positive integer and check whether the number is 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.

R If Statement 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 are outside the If block.