Nested If - Else
Part of the Fundamentals section of Coddy's R journey — lesson 25 of 78.
Sometimes two options aren't enough. What if you need to check multiple conditions and handle each one differently? You can place an if-else statement inside another if or else block to create more complex decision paths.
score <- 85
if (score >= 90) {
print("Grade: A")
} else {
if (score >= 80) {
print("Grade: B")
} else {
print("Grade: C or below")
}
}R first checks if the score is 90 or above. Since 85 doesn't meet that condition, it moves to the else block.
Inside, another if checks if the score is at least 80. Since 85 passes this test, it prints "Grade: B".
R provides a cleaner way to write this using else if:
score <- 85
if (score >= 90) {
print("Grade: A")
} else if (score >= 80) {
print("Grade: B")
} else {
print("Grade: C or below")
}Both approaches work the same way, but else if keeps your code flatter and easier to read. You can chain as many else if blocks as needed, and R will execute only the first block whose condition is true.
Challenge
EasyCreate a ticket pricing system using nested if-else or else if statements to determine the ticket price based on age.
You are provided with the following variable:
age <- 25Write a series of conditions to determine and print the ticket price based on these rules:
- If age is less than 5, print
"Free" - If age is between 5 and 12 (inclusive), print
"$5" - If age is between 13 and 17 (inclusive), print
"$8" - If age is between 18 and 64 (inclusive), print
"$12" - If age is 65 or older, print
"$7"
Use the print() function for your output.
Cheat sheet
You can nest if-else statements inside each other to check multiple conditions:
score <- 85
if (score >= 90) {
print("Grade: A")
} else {
if (score >= 80) {
print("Grade: B")
} else {
print("Grade: C or below")
}
}A cleaner approach is using else if to chain multiple conditions:
score <- 85
if (score >= 90) {
print("Grade: A")
} else if (score >= 80) {
print("Grade: B")
} else {
print("Grade: C or below")
}R evaluates conditions in order and executes only the first block whose condition is true. You can chain as many else if blocks as needed.
Try it yourself
# Variable provided
age <- 25
# TODO: Write your code below
# Use nested if-else or else if statements to determine the ticket price
# based on the age rules providedThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values