i

R Programming Complete Tutorial

R If Statement

Decision Branching

Decision making is an integral part of programming. In R, like other languages, there are several cases where we might wish for conditionally execute any code. R provides if, else if and switch statement for decision making. In the following section, we are going to follow them one by one. In every section, we will start with the basic syntax, then learn the flow diagram and finally finish with an example.

Let’s start with the basic if command:

If Statement

This basic form of conditional statement checks whether a condition is true or false. If the condition is true, the statement gets executed, but if it is false, nothing happens. Here, in this condition, we can use a logical or relational operation that will return a TRUE FALSE RESULT. This flow diagram will give us a more precise idea.

Flow diagram:

First, it checks the condition, if the condition is true, it will execute the statement and exit, and in case of false, it will directly exit the flow.

If Syntax:

If condition follows the below syntax.

Example:

This, if statement will inform when we have a fever.

The first line of code will take input from the user and store it in the temperature variable. Then this condition will check whether the temperature is higher than 98 or not. If TRUE, the program will print- You are suffering from fever.

Now we will go to the if...else statement.