Decision Making in R
In R programming, Decision Making statements also called conditional statement help to decide whether to execute a block of code or not, based on a condition. In this tutorial, we use decision making statements available in R language through examples.
The following are detailed of decision making statements in R.
- R if statement
- R if-else statement
- R if-else-if statement
- R switch statement
R If Statement
In If statement, a condition is evaluated using boolean expression TRUE/FALSE. If the result is TRUE, then a block of statements are executed.
Example R:
a <- 1
if (a == 1) {
print("a is equal to 1.")
}
print("End of programme")
#output
[1] "a is equal to 1."
[1] "End of programme"
If the condition evaluates to FALSE, then if-block is not executed, and it will continue with the statements after the If statement.
Example R:
a <- 2
if (a == 1) {
print("a is equal to 1.")
}
print("End of programme")
#output
[1] "End of programme"
R if-else statement
A condition is evaluated using boolean expression. If TRUE, then statements in if-block are execute, otherwise else-block statements are executed.
Example R:
a <- 2
if (a == 1) {
print("a is 1.")
} else {
print("a is not 1.")
}
print("End of program.")
#output:
[1] "a is not 1."
[1] "End of program."
R if-else-if statement
This is a chained if-else statement. It will scan and evaluate the conditions 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:
a <- 5
if (a == 2) {
print("a is 2.")
} else if (a == 5) {
print("a is 5.")
} else if (a == 10) {
print("a is 10.")
}
print("End of program.")
#output:
[1] "a is 5."
[1] "End of program."
R switch statement
In R Switch statement, an expression is evaluated and based on the result of matching index or value, a value is selected from a list of values.
Example R of matching index:
y <- 2
x <- switch(
y,
"Green",
"Yellow",
"Red",
"Blue"
)
print(x)
#output:
[1] "Yellow"
Example R of matching value:
y <- "R"
x <- switch(
y,
"G"="Green",
"Y"="Yellow",
"R"="Red",
"B"="Blue"
)
print(x)
#output:
[1] "Red"
Conclusion
In this R tutorial, we learned about decision making also called as conditional statements – If, If-Else, If-Else-If, and Switch.
