If - Else
Part of the Fundamentals section of Coddy's R journey — lesson 23 of 78.
With a basic if statement, code either runs or it doesn't. But what if you want to do something different when the condition is false? That's where else comes in.
The else block provides an alternative path when the if condition evaluates to FALSE:
temperature <- 18
if (temperature > 30) {
print("It's hot outside!")
} else {
print("It's not too hot.")
}In this example, since 18 is not greater than 30, R skips the first block and executes the else block instead, printing "It's not too hot."
This structure guarantees that exactly one of the two blocks will always run. Either the condition is true and the first block executes, or it's false and the else block executes:
score <- 75
if (score >= 60) {
print("You passed!")
} else {
print("Try again.")
}Since 75 is greater than or equal to 60, this prints "You passed!" The else block is completely skipped.
Challenge
EasyUse an if-else statement to print different messages based on whether a condition is true or false.
You are provided with the following variables:
age <- 16
required_age <- 18Write an if-else statement that checks if age is greater than or equal to required_age.
- If the condition is
TRUE, print"Access granted" - If the condition is
FALSE, print"Access denied"
Use the print() function for your output.
Cheat sheet
The else block provides an alternative path when the if condition is FALSE:
temperature <- 18
if (temperature > 30) {
print("It's hot outside!")
} else {
print("It's not too hot.")
}This structure guarantees that exactly one of the two blocks will always run:
score <- 75
if (score >= 60) {
print("You passed!")
} else {
print("Try again.")
}Try it yourself
# Variables provided
age <- 16
required_age <- 18
# TODO: Write your if-else statement below to check if age >= required_age
# Print "Access granted" if TRUE, "Access denied" if FALSEThis 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