Lesson contents

R — Scalar conditions with if and else

In R, if tests one logical value. An else if chain checks successive conditions, and the first true branch supplies the selected result.

A simple example

Follow one branch

  1. Start with n is 2
  2. Do this Is n positive?
  3. Result yes
The condition selects the first branch. Changing the value to zero selects the other branch.
Lesson.R
n <- 2
if (n > 0) {
  cat("yes\n")
} else {
  cat("no\n")
}
Output
yes
Advertisements

Classify a stock level

if expects one nonmissing logical value. A scalar stock count produces one classification. For a vector of counts, use a vectorized operation or iterate explicitly.

On the shelf: 3 books. Low-stock limit: 5 books. Shelf notice: Order soon.
Decide when to restock

A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.

Run the example

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

Rscript Lesson.R
Lesson.R
stock <- 3L
status <- if (stock == 0L) {
  "sold out"
} else if (stock <= 5L) {
  "order soon"
} else {
  "in stock"
}
cat(status, "\n", sep = "")
Output
order soon

The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.

Try it yourself

Try the boundary values 0, 5, and 6.

Check your answer

They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.

An Introduction to R

Related tags

  • R
  • conditions
  • branching
  • comparison