if / else
if and else let R choose what to do, like 'if it is cold wear a coat, else wear a t-shirt'. The code in a block only runs when its question is TRUE.
In this page:
Syntax
if (condition) {
# runs when TRUE
} else if (other_condition) {
# runs when other_condition is TRUE
} else {
# otherwise
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Putting
elseon a new line after the closing}at top level, as in}newlineelse {, which is a syntax error outside braces. - Passing a vector of length greater than 1 as the condition, which is an error in recent R versions; use
any()orall()orifelse(). - Using
=instead of==in the condition, which assigns rather than compares.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: