If/Else & Else-If
Chains in R
Learn to control the flow of your R programs using conditional logic: if, else, and else if statements.
What Is Conditional Logic?
Every program needs to make decisions. Should we print a greeting or a warning? Should we calculate a discount or charge full price? Conditional statements let your code choose which path to take based on whether a condition is TRUE or FALSE.
The if Statement
The simplest conditional: execute a block of code only when a condition is TRUE. If it's FALSE, the block is skipped entirely.
How if Flows
Adding else: Two Paths
When you need two possible outcomes, pair if with else. The else block executes whenever the condition is FALSE: you always get exactly one of the two paths.
if/else Flowchart
The else if Chain
When you have three or more possible outcomes, use an else if chain. R checks each condition in order and executes the first one that is TRUE.
if vs else if vs Nested if
How to Write a Conditional
Example 1: Pass or Fail
Example 2: Letter Grade
Why Order Matters
Watch what happens if we reverse the order and check the least specific condition first:
Example 3: Nested Conditions
Logical Operators in Conditions
You can combine multiple conditions into a single test using logical operators:
Common Mistakes
Summary Comparison
| Structure | Blocks That Run | Use When | |
|---|---|---|---|
| if | Single condition | 0 or 1 | One optional action |
| if/else | Two branches | Exactly 1 | Binary decision |
| else if chain | Multiple branches | Exactly 1 | Mutually exclusive outcomes |
| Nested if | if inside if | Varies | Sub-conditions |
| Separate ifs | Independent blocks | 0 to all | Independent checks |
Question 1 of 5
What does the following code print?
x <- 15
if (x > 20) { print("A") } else { print("B") }
Question 2 of 5
In an else if chain, how many code blocks execute when a condition is TRUE?
Question 3 of 5
What is the value of grade after this code runs?
score <- 95
if (score >= 90) { grade <- "A" }
else if (score >= 80) { grade <- "B" }
else { grade <- "C" }
Question 4 of 5
Which line causes an error in R?
Question 5 of 5
What is the difference between using two separate if statements versus an if/else if chain?