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.
R conditional statements are used when a program has to choose between different paths. For example, an R script may print a message only when a value crosses a threshold, classify a score into a grade, or select one result from a group of options.
The following are detailed tutorials for each of the decision making statements in R.
What is a decision making statement in R?
A decision making statement in R is a control structure that evaluates a condition and then decides which statement or block should run. The condition must evaluate to a logical value, usually TRUE or FALSE.
For scalar decisions, R commonly uses if, if...else, if...else if...else, and switch(). For vectorized decisions, R also provides functions such as ifelse(), but ifelse() is different from the regular control-flow if statement.
R conditional statements at a glance
| R decision making statement | When to use it | Example use case |
|---|---|---|
if | Run a block only when one condition is TRUE. | Print a warning when a value is negative. |
if...else | Choose between two possible branches. | Print pass or fail based on marks. |
if...else if...else | Choose one branch from many conditions. | Classify marks into grades. |
switch() | Select a value or expression based on an index or name. | Return a label for a selected option. |
The examples below show each R decision making statement in a simple form. The condition examples use == for equality comparison, not assignment.
R If Statement
In If statement, a condition (boolean expression) is evaluated. If the result is TRUE, then a block of statements are executed.
The basic syntax of an R if statement is shown below.
if (condition) {
# statements to run when condition is TRUE
}
Example.R
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
a <- 10
if (a == 6) {
print("a is 6.")
}
print("End of program.")
Output
[1] "End of program."
Here, a == 6 is FALSE, so the block inside if is skipped. The final print statement runs because it is outside the if block.
R If-Else Statement
A boolean expression is evaluated and if TRUE, statements in if-block are execute, otherwise else-block statements are executed.
The else block gives one alternate path when the if condition is not satisfied.
if (condition) {
# statements when condition is TRUE
} else {
# statements when condition is FALSE
}
Example.R
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."
Since a == 6 is FALSE, R runs the else block and then continues with the statements after the complete if...else structure.
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.
Use an R if...else if...else ladder when there are more than two possible outcomes. R checks conditions in order and executes only the first matching branch.
if (condition_1) {
# statements when condition_1 is TRUE
} else if (condition_2) {
# statements when condition_2 is TRUE
} else {
# statements when no earlier condition is TRUE
}
Example.R
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."
In this example, the first condition is false and the second condition is true. Therefore, R prints "a is 10.". The later else if condition is not evaluated after the match is found.
R if else if ladder for grade classification
The order of conditions is important in an R if...else if ladder. For range-based decisions, place the highest or most specific condition first.
marks <- 82
if (marks >= 90) {
grade <- "A"
} else if (marks >= 75) {
grade <- "B"
} else if (marks >= 60) {
grade <- "C"
} else if (marks >= 40) {
grade <- "D"
} else {
grade <- "Fail"
}
print(grade)
Output
[1] "B"
Although marks >= 60 is also true for 82, R stops at the first true condition, marks >= 75.
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.
The switch() function is useful when the program must select one value from a fixed set of choices. The selection can be based on a number or a name.
result <- switch(expression, option_1, option_2, option_3)
Example.R
y <- 3
x <- switch(
y,
"Good Morning",
"Good Afternoon",
"Good Evening",
"Good Night"
)
print(x)
Output
[1] "Good Evening"
Here, y is 3, so switch() selects the third value from the list and assigns it to x.
R switch statement with named choices
A named switch() statement can be easier to read when choices are labels such as "add", "subtract", or "divide".
operation <- "multiply"
a <- 4
b <- 5
answer <- switch(
operation,
add = a + b,
subtract = a - b,
multiply = a * b,
divide = a / b
)
print(answer)
Output
[1] 20
Since operation is "multiply", R evaluates the named expression multiply = a * b.
Multiple conditions in R decision making statements
R conditions can combine more than one comparison. Use && when both scalar conditions must be true. Use || when at least one scalar condition must be true.
age <- 21
has_id <- TRUE
if (age >= 18 && has_id == TRUE) {
print("Allowed")
} else {
print("Not allowed")
}
Output
[1] "Allowed"
For scalar decision making with if, && and || are usually clearer than the vectorized operators & and |. Use vectorized operators when you intentionally compare vectors element by element.
Comparison operators used in R conditional statements
Most R conditional statements use comparison operators inside the condition. These operators return logical values such as TRUE or FALSE.
| Operator | Meaning in an R condition | Example |
|---|---|---|
== | Equal to | a == 10 |
!= | Not equal to | a != 10 |
> | Greater than | a > 10 |
>= | Greater than or equal to | a >= 10 |
< | Less than | a < 10 |
<= | Less than or equal to | a <= 10 |
A common mistake is to use assignment when a comparison is needed. Inside a condition, use == to test equality.
R if statements and vectorized ifelse()
The regular R if statement is meant for one logical decision. When you need to apply a condition across every element in a vector, use ifelse().
scores <- c(35, 60, 78, 92)
result <- ifelse(scores >= 40, "Pass", "Fail")
print(result)
Output
[1] "Fail" "Pass" "Pass" "Pass"
Use if...else for control flow and use ifelse() for element-by-element conditional results in vectors.
Common mistakes in R decision making statements
- Using
elifin R: R useselse if, notelif. - Using
=instead of==in a condition: Use==when you want to compare two values. - Writing broad range checks first: In an
if...else ifladder, the first true condition wins. - Passing a vector condition to
if: Use a single logical value forif. Useifelse()for vectors. - Putting
elseon a detached line: Keepelsewith the closing brace of the previous block, as in} else {.
QA checklist for R conditional statements examples
- Confirm that each R
ifcondition evaluates to one logical result for scalar control flow. - Check that every
else ifcondition is written afterelseand before its code block. - Verify that
switch()examples use the correct numeric position or named choice. - Run each R example and compare the actual console output with the output shown in the tutorial.
- Check that range-based examples place the most restrictive or highest-priority condition first.
FAQs on R decision making and conditional statements
What is a conditional statement in R?
A conditional statement in R evaluates a condition and runs code based on whether the condition is TRUE or FALSE. Common examples are if, if...else, if...else if...else, and switch().
What are the main types of R decision making statements?
The main decision making statements in this tutorial are if, if...else, if...else if...else, and switch().
Does R use elif for conditional statements?
No. R does not use elif. The correct R syntax is else if, written as two words.
What does == mean in an R condition?
The operator == checks equality. For example, a == 10 returns TRUE when the value of a is equal to 10.
When should I use ifelse() instead of if in R?
Use if for a single control-flow decision. Use ifelse() when you want to apply a condition to each element of a vector and return a vector of results.
Conclusion on R decision making statements
In this R tutorial, we learned about R decision making / conditional statements – If, If-Else, If-Else-If, and Switch. Use if for a single condition, if...else for two branches, if...else if...else for multiple ordered conditions, and switch() when you need to select from fixed choices.
TutorialKart.com