How to create nested if statements in R
Introduction
The if statement in R executes a single block of statements based on a logical expression.
The syntax is as follows:
if (expression) {
statement
}
The expression in the code is usually a boolean expression (true or false). The program above will only execute the provided statement if the expression is true.
Code
Let’s write a simple code to illustrate the if statement.
x <- 1y <- 2if (y > x){print("y is greater than x")}
In the code above, we can see that the expression is true, so the statement is executed.
An if statement can also come with an else block; this is called an if-else statement.
The if-else statement
The if-else statement has two blocks of statements and executes one of them based on certain logical expressions.
The syntax is as follows:
if (expression){
statement_1(s)
---
}else{
statement_2(s)
}
The code above will only execute the if block if the expression is true. If the expression is false, then the program executes statement_2 in the else block.
Code
x <- 1y <- 2if (y < x){print("y is less than x")}else{print("x is less than y")}
In the code above, the value of x is less than that of y, so the first condition is not true. The else condition tells us that if otherwise (i.e. the expression is not true), it should return another statement from its own block.
Nested if statements
A nested if statement is an if statement inside another if statement.
The code below illustrates how to create nested if statements.
x <- 30# creating the first if blockif (x > 10) {print("x is greater than ten")# creating another if blockif (x > 20) {print("and also greater than 20!")# closing the second if block} else {print("but less than 20.")}# closing the first if block} else {print("x is less than 10.")}
Explanation
-
Line 1: We create an integer variable
x. -
Line 4: We create the first
ifblock and give a condition(x > 10), followed by the statement to be executed in line 5 if the given condition istrue. -
Line 8: We create the second
ifblock and give a condition(x > 20), followed by the statement to be executed in line 9 if the provided condition istrue. -
Line 12: We use the
elsestatement/block to close the secondifblock. If the expression in the secondifblock is nottrue, thenRshould execute the statement provided in line 13. -
Line 17: We use the
elsestatement/block to close the firstifblock. If the expression in the firstifblock is nottrue, thenRshould execute the statement provided in line 18.