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
- Start with 2 and −1
- Do this Test each sign
- Result positive, other
cat(ifelse(c(2, -1) > 0, "positive", "other"), sep = "\n")
positive other
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.
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
totals <- c(4999L, 5000L, NA_integer_)
labels <- ifelse(totals >= 5000L, "free", "paid")
writeLines(ifelse(is.na(labels), "NA", labels))
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.