Related Tags

r
communitycreator

# How to create nested if statements in R

Onyejiaku Theophilus Chidalu

### 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 <- 1
y <- 2

if (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 <- 1
y <- 2

if (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 block
if (x > 10) {
print("x is greater than ten")

# creating another if block
if (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 if block and give a condition (x > 10), followed by the statement to be executed in line 5 if the given condition is true.

• Line 8: We create the second if block and give a condition (x > 20), followed by the statement to be executed in line 9 if the provided condition is true.

• Line 12: We use the else statement/block to close the second if block. If the expression in the second if block is not true, then R should execute the statement provided in line 13.

• Line 17: We use the else statement/block to close the first if block. If the expression in the first if block is not true, then R should execute the statement provided in line 18.

RELATED TAGS

r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time