Learn/R/4. Making decisions
Lesson 4 of 8
Sign in

R, lesson 4

Making decisions

Programs become useful when they react to their input: charge a child less than an adult, warn when a battery is low, say "freezing" below zero. In R the tool for this is if.

The condition goes in parentheses, and the code to run goes in braces. If the condition is FALSE, R skips the block.

else and else if

Add else for the other case, and chain else if to test several conditions in order. R runs the first block whose condition is true and skips the rest:

One R detail trips people up: else must be on the same line as the closing brace } before it. If } ends a line on its own, R thinks the if is finished and then fails on the lonely else.

2 exercises to try what you just read.

Exercise 1

Cinema tickets

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

Comparison operators

OperatorMeaning
==equal (two = signs; one = is assignment)
!=not equal
<, <=, >, >=less / greater than

They work on text too: "apple" == "apple" is TRUE, and the comparison is case-sensitive.

Combining conditions

  • && is "and": true only if both sides are true.
  • || is "or": true if at least one side is true.
  • ! is "not": flips TRUE and FALSE.

&& and || stop as soon as the answer is known, and they expect a single TRUE or FALSE on each side. R also has single & and |, which compare whole vectors element by element; you will use those for filtering data later. Inside if, use the doubled forms.

The condition of an if must be exactly one TRUE or FALSE. If it is NA (for example because a number failed to convert), R stops with an error, which is better than silently taking the wrong branch.

if gives back a value

In R, if is an expression, so you can store its result:

For a quick check on whole numbers, the remainder operator helps: n %% 2 == 0 is TRUE for even numbers.

Further reading

  • An Introduction to R, section "Control statements"
  • R Language Definition, section "if"
  • R documentation: Logical operators

Read a person's age (a whole number) and print the ticket type and price:

  • under 12: Child: 5
  • 12 to 64: Adult: 9
  • 65 or older: Senior: 6

Sample input:

Sample output:

Read a year and print leap if it is a leap year, or common if it is not. A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap years only if they are also divisible by 400.

Sample input:

Sample output:

temp <- -3
if (temp < 0) {
  cat("Freezing!\n")
}
if (temp < 0) {
  cat("Freezing\n")
} else if (temp < 15) {
  cat("Cool\n")
} else {
  cat("Warm\n")
}
age <- 70
student <- FALSE
if (age >= 65 || student) {
  cat("Discount applies\n")
}
label <- if (temp < 0) "ice" else "water"
30
Adult: 9
2024
leap