Lesson contents

R — Vectorized conditional values with ifelse

ifelse applies a logical test element by element and constructs a result with the same shape as the test. Scalar if and else select one branch for a single condition.

A simple example

Choose a word for each number

  1. Start with 2 and −1
  2. Do this Test each sign
  3. Result positive, other
ifelse chooses a result separately for each element of the vector.
Lesson.R
cat(ifelse(c(2, -1) > 0, "positive", "other"), sep = "\n")
Output
positive
other
Advertisements

Label every order that qualifies for free delivery

Classify a vector of order totals using a threshold of 5,000 cents. A missing total should stay missing in the result. Use ifelse for labels across a vector. Numeric branches containing unsafe operations may still be evaluated on the full input, so validate or subset numeric data before such calculations.

4,999 cents: Paid delivery. 5,000 cents: Free delivery. Missing total: Unknown.
Choose delivery labels in a batch

A bookshop offers free delivery on orders of at least 5,000 cents. The boundary matters because 4,999 still incurs a fee. An order with a missing total stays unknown until the till receives a price.

Run the example

Use R 4.x. Run these commands from the directory containing the example.

Rscript --vanilla Lesson.R
Lesson.R
totals <- c(4999L, 5000L, NA_integer_)
labels <- ifelse(totals >= 5000L, "free", "paid")
writeLines(ifelse(is.na(labels), "NA", labels))
Output
paid
free
NA

The first order is one cent below the threshold and the second exactly qualifies. Comparing NA to the threshold yields NA, which propagates to the label.

Try it yourself

What label should 5,001 cents receive? What if the total is NA?

Check your answer

The higher total receives free. A missing total yields NA because the comparison has no known truth value.

R Language Definition

Related tags

  • R
  • conditional selection
  • expressions
  • zero division