if / else
Try it yourself →Branching based on conditions.
Syntax
if (condition) { ... } else { ... }Description
The condition is written in parentheses; if true, the first block executes. else must be on the SAME line as the closing }.
Example
age <- 20
if (age >= 18) {
cat("Adult\n", sep="")
} else {
cat("Child\n", sep="")
}Expected output
Adult
When to use?
Decision making, input control.
Common mistakes
- ⚠️ Putting else on a new line causes an error; use } else { on the same line.