if / else
In this page:
if / else
An if statement runs a block only when its condition is TRUE; an optional else runs otherwise. The condition must evaluate to a single logical value, not a vector -- using a vector condition triggers an error or warning depending on the R version. else must appear on the same line as the closing brace of the if block when written across multiple lines.
Warning: The condition in if() must be a single TRUE/FALSE value, not a vector -- use ifelse() or all()/any() for vectorized conditions.
Example: if / else
score <- 85
if (score >= 90) {
cat("Grade: A\n")
} else if (score >= 70) {
cat("Grade: B\n")
} else {
cat("Grade: C\n")
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: