TExcelTAD
Home › R › R If...Else

R If...Else

Programs need to make decisions. The if statement runs a block of code only when a condition is TRUE.

r · try it yourself
temperature <- 28
if (temperature > 25) {
  print("It's a hot day")
}
[1] "It's a hot day"

The condition goes inside parentheses, and the code to run goes inside braces.

else and else if

Add else for the alternative, and chain else if for more cases. R checks the conditions from top to bottom and runs the first block whose condition is TRUE:

r · try it yourself
grade <- function(score) {
  if (score >= 90) {
    "A"
  } else if (score >= 75) {
    "B"
  } else if (score >= 50) {
    "C"
  } else {
    "F"
  }
}
grade(95)
grade(80)
grade(42)
[1] "A"
[1] "B"
[1] "F"

Note: In a script, else must be on the same line as the closing } of the if block. If } ends a line, R considers the if finished and a following else on a new line is a syntax error.

if returns a value

if is an expression: it evaluates to the value of the branch that ran. You can assign its result directly:

r · try it yourself
stock <- 0
status <- if (stock > 0) "available" else "sold out"
status
[1] "sold out"

Nested conditions and logical operators

Combine conditions with && and ||, or nest if statements:

r · try it yourself
age <- 20
member <- TRUE
if (age >= 18 && member) {
  cat("Full access\n")
} else if (age >= 18) {
  cat("Please sign up\n")
} else {
  cat("Too young\n")
}
Full access

The condition must be a single TRUE or FALSE

if needs exactly one logical value. A missing value or a vector of length 2 is an error:

r · try it yourself
x <- c(3, 8)
if (x > 5) print("big")
Error in if (x > 5) print("big") : the condition has length > 1

To ask "is any/every element bigger?", use any(x > 5) or all(x > 5).

ifelse(): vectorised if

To choose a value for each element of a vector, use ifelse(test, yes, no):

r · try it yourself
temps <- c(12, 25, 31, 18)
ifelse(temps > 20, "warm", "cold")
scores <- c(45, 72, 90)
ifelse(scores >= 50, "pass", "fail")
[1] "cold" "warm" "warm" "cold"
[1] "fail" "pass" "pass"

switch()

When you compare one value against many options, switch() is more compact than a long else if chain. The last unnamed argument is the default:

r · try it yourself
unit_name <- function(code) {
  switch(code,
    km = "kilometres",
    mi = "miles",
    m = ,                 # falls through to the next value
    metre = "metres",
    "unknown unit")
}
unit_name("km")
unit_name("m")
unit_name("ft")
[1] "kilometres"
[1] "metres"
[1] "unknown unit"

Test yourself

What does if (5 > 3) "yes" else "no" return?

  1. "no"
  2. "yes"
  3. TRUE
  4. NULL

Which function picks a value for every element of a vector?

  1. if
  2. switch
  3. ifelse
  4. while

What happens with if (c(TRUE, FALSE)) ... in R 4.2+?

  1. Only the first element is used
  2. An error: the condition has length > 1
  3. Both branches run
  4. It returns NA