Written and maintained by CASRAI Editorial Board
Last updated
An if statement in R runs a block of code only when a condition is true, and an optional else runs a different block when it is not. The condition must be a single TRUE or FALSE value, and that one rule explains most of the errors people hit. This guide covers the syntax, what counts as a valid condition, the line-break rule for else, and when to use ifelse() or switch() instead. It also covers what people search for as the “r programming if statement”: it is the same construct, described in the R documentation as part of the language’s control flow.
What it is used for in research
Analysis scripts make decisions constantly: stop if a data file is empty, apply a transformation only when a variable is on the wrong scale, or report one message when a test result crosses a threshold you set in advance. An if statement is the tool for a single decision that applies to the whole script at that point. When the decision must be made separately for every element of a vector (every row of a column, for example), the base R documentation points to ifelse() instead, covered in ifelse in R. Writing these decisions as code rather than making them by hand is also part of what makes an analysis repeatable; see computational reproducibility.
Install or access
The if statement is part of the R language itself, so there is nothing extra to install. Download R from the Comprehensive R Archive Network (CRAN) at cran.r-project.org. You can type the examples below at the R console, or run them from a script in any editor. If you prefer not to install anything locally, see RStudio on the cloud.
Step-by-step: writing an if statement
1. Write a basic if
The form documented in the R help page ?Control is if(cond) expr. Put the code to run inside braces:
x <- 7
if (x > 5) {
print("x is greater than 5")
}
Because 7 is greater than 5, R prints [1] "x is greater than 5". If the condition were false, nothing would print.
2. Add an else branch
The documented form is if(cond) cons.expr else alt.expr. The first expression runs when the condition is true, the second when it is false:
p <- 0.03
if (p < 0.05) {
print("p is below the 0.05 threshold")
} else {
print("p is not below the 0.05 threshold")
}
This is an illustration of control flow only; the threshold is a placeholder you would set from your own analysis plan.
3. Chain choices with else if
The R Language Definition gives the syntax as if ( statement1 ) statement2 else statement3, and statement3 can itself be another if. That is how an “else if” chain works: each else is followed by a new if.
classify <- function(x) {
if (is.na(x)) {
"missing"
} else if (x > 5) {
"high"
} else {
"low"
}
}
classify(7)
This returns [1] "high". Checking is.na(x) first keeps a missing value from reaching the comparison, which matters because the condition must not be NA (see Troubleshooting).
4. Use the value an if statement returns
Per ?Control, if returns the value of the expression that was evaluated, so you can assign the result directly:
y <- if (x > 5) "high" else "low"
y
With x equal to 7, y is "high".
Output and how to read it
An if statement produces output only if the chosen branch prints or returns something visible. Three behaviours are worth knowing, all from the R documentation:
- The condition.
condis documented as a length-one logical vector that is notNA. Other types are coerced to logical if possible, so a number works as a condition. - Numbers as conditions. The R Language Definition says a numeric condition selects the else branch when the first element is zero, and the first branch otherwise. It also says that a value of any type other than logical or numeric signals an error.
- No else and a false condition. The result is
NULL, returned invisibly. Soz <- if (x > 100) "big"leaveszasNULL, which can surprise you later if you usezas if it held a string.
Troubleshooting
The else is on a new line and R reports an unexpected else
The R Language Definition states that when the if statement is not in a block, the else, if present, must appear on the same line as the end of the preceding statement. ?Control gives the same warning: you should not have a newline between } and else when typing at the keyboard or running through source. This fails at the console:
if (x > 5) {
print("high")
}
else {
print("low")
}
The fix is to keep the else on the same line as the closing brace: } else {. The help page also describes always using braces for if clauses as one (somewhat extreme) attitude of defensive programming; braces are good practice here regardless.
The condition has more than one element
Conditions of length greater than one are an error according to ?Control. This happens when you pass a whole column, such as if (df$score > 50). If you need one answer per element, use ifelse(). If you need one answer for the whole vector, reduce it to a single value first, with a function such as any() or all().
One caution: the older R Language Definition says only the first element of the condition is used. The current help page says a longer condition is an error. Write code to the help page, which describes current R, and you will not depend on the older behaviour.
The condition is NA
The documented condition is a logical value that is not NA, so a missing value cannot be used as a condition. Test for it first with is.na(), as in the classify() example above.
Using = instead of ==
A single = assigns; it does not compare. Write if (x == 5) to test equality.
Free alternatives
These are all part of base R, so they need no extra packages. The notes come from the help pages for ifelse and switch.
| Function | Use it when | What the documentation says |
|---|---|---|
if / else |
One decision with one TRUE/FALSE answer | The base R manual calls if(test) yes else no much more efficient and often much preferable to ifelse() when the test has length one. |
ifelse(test, yes, no) |
A decision for every element of a vector | Returns a value with the same shape as test; missing values in test give missing values in the result. See ifelse in R. |
switch(EXPR, ...) |
Choosing one of several named alternatives | With a character EXPR, the string is matched exactly to the names of the alternatives; an unnamed alternative acts as the default. If nothing is selected it returns NULL, invisibly. |
Inside a loop, an if statement is how you skip or stop an iteration. See for loops in R for the loop side of that pattern.
FAQ
What is an r programming if statement?
It is the same thing as an R if statement: the control-flow construct if(cond) expr, with an optional else. R treats if and else as reserved words.
Can an if statement return a value in R?
Yes. It returns the value of the expression evaluated, or NULL invisibly if none was, which can happen when there is no else.
Why does R say unexpected else?
At the console or through source, a line break between the closing brace and else ends the if statement early. Put } else { on one line.
Should I use if or ifelse?
Use if for a single TRUE/FALSE test and ifelse() when the test covers a whole vector, as the base R manual advises.
Sources
- R Core Team, R Language Definition, section on if (CRAN), checked 2026-10-29.
- R Documentation, Control Flow (?Control), base package, checked 2026-10-29.
- R Documentation, Conditional Element Selection (?ifelse), checked 2026-10-29.
- R Documentation, Select One of a List of Alternatives (?switch), checked 2026-10-29.








