What are if-elif-else statements in R?

Overview

if-elif-else statements in R allow us to build programs that can make decisions based on certain conditions.

The if-elif-else statement consists of three parts:

  • if
  • elif
  • else

These parts combine to execute blocks of statements based on logical expressions.

The if statement

The if statement executes a single block of statements based on a certain logical expression.

The syntax is as follows:

if (expression) {
  statement
}

The expression in the line of code above is usually a boolean expression (true or false). The program above will only execute the provided statement if the expression is true.

Code

x <- 1
y <- 2
if (y > x){
print("y is greater than x")
}

The if-else statement

The if-else statement has two blocks of statements and executes 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, x is less than y, so the first condition is not true. The else condition tells us that if otherwise, meaning the expression is not true, it should return another statement from its own block.

The if-elif-else statement

The elif statement, short for else if or “otherwise if”, is added to the if-else block when there are many more conditions. The if-elif-else statement basically consists of several blocks.

The syntax is as follows:

if (expression){
    statement_1(s)
    ---
}else if(expression2){
    statement_2(s)
} else{
    statement_3(s)
}

The code above will execute for just a block when it finds an expression to be true.

Code

x <- 1
y <- 2
if (y < x){
print("y is less than x")
}else if(y > x){
print("y is greater than x")
}else{
print("x is greater than y")
}

Free Resources