R Decision Making

In R programming, Decision Making statements help to decide whether to execute a block of code or not, based on a condition. Decision making is an important aspect in any programming language. Decision Making statements are also called Conditional statement.

In this tutorial, we list out decision making statements available in R language, and go through examples for each of them.

The following are detailed tutorials for each of the decision making statements in R.

R If Statement

In If statement, a condition (boolean expression) is evaluated. If the result is TRUE, then a block of statements are executed.

Example.R

</>
Copy
a <- 6

if (a == 6) {
  print("a is 6.")
}

print("End of program.")

Output

[1] "a is 6."
[1] "End of program."

If the condition evaluates to FALSE, then if-block is not executed, and the execution continues with the statements after If statement.

Example.R

</>
Copy
a <- 10

if (a == 6) {
  print("a is 6.")
}

print("End of program.")

Output

[1] "End of program."

R If-Else Statement

A boolean expression is evaluated and if TRUE, statements in if-block are execute, otherwise else-block statements are executed.

Example.R

</>
Copy
a <- 10

if (a == 6) {
  print("a is 6.")
} else {
  print("a is not 6.")
}

print("End of program.")

Output

[1] "a is not 6."
[1] "End of program."

R If-Else-If Statement

This is kind of a chained if-else statement. From top to down, whenever a condition evaluates to TRUE, corresponding block is executed, and the control exits from this if-else-if statement.

Example.R

</>
Copy
a <- 10

if (a == 6) {
  print("a is 6.")
} else if (a == 10) {
  print("a is 10.")
} else if (a == 20) {
  print("a is 20.")
}

print("End of program.")

Output

[1] "a is 10."
[1] "End of program."

R Switch Statement

In R Switch statement, an expression is evaluated and based on the result, a value is selected from a list of values.

Example.R

</>
Copy
y <- 3

x <- switch(
  y,
  "Good Morning",
  "Good Afternoon",
  "Good Evening",
  "Good Night"
)

print(x)

Output

[1] "Good Evening"

Conclusion

In this R tutorial, we learned about R decision making / conditional statements – If, If-Else, If-Else-If, and Switch.