Conditionals & Loops

Conditionals & Loops in R: --- A parcel sorting office runs a single belt down the middle of the floor.


The Analogy: The Sorting Office Diverter Lever and the Inline Stamping Head

A parcel sorting office runs a single belt down the middle of the floor. Half way along it stands an operator at a diverter lever. A parcel arrives, the operator reads the label, and pushes the lever left for the local round or right for the trunk van. One parcel, one look, one decision, and while the operator is deciding, the belt in front of the lever is not moving. The lever is exactly as fast as the person pulling it, and it answers one question about one parcel.

Further along the same belt there is no operator at all. A steel bar spans the belt carrying two ink heads, and underneath it is a weigh plate. Somebody set the rule card on the bar this morning: under one kilo takes the blue stamp, everything else takes the red one. Parcels pass under the bar at running speed and come out stamped. Nobody looks at any individual parcel. The rule was stated once and it applies to every parcel that goes past, in one continuous pass, and the belt never stops.

Which mechanism belongs where is decided entirely by the shape of the question. "Is the trunk van already loaded, and if so should the whole shift divert to the local round?" is one question about one state of the world, asked once, and the answer changes what the office does next. That is the lever. "Mark each parcel with the band its weight falls into" is the same question asked of every parcel independently, and the answers do not affect each other. That is the stamping head. Reaching for the lever when the stamping head was the right tool means an operator pulling it eleven thousand times a shift.

The two failure modes are worth learning as pictures, because both have exact counterparts in R. Hand the lever operator an entire trolley of parcels and ask "left or right" -- there is no answer. The operator can only read the top label, and any sensible foreman stops the belt rather than diverting the whole trolley on the strength of one parcel. That is if given a vector. And the stamping head has its own trap: the bar carries both ink heads and they both track the whole belt, so the blue applicator passes over every parcel including the heavy ones and the red over every parcel including the light ones, and only then is the unwanted impression wiped off. If one of those two rules is expensive, or is nonsense for some parcels, it has already been applied to all of them before anything was discarded. That is ifelse.


Syntax or Core Structure

if takes exactly one logical value and evaluates one branch. ifelse takes a whole logical vector and returns a vector of the same length. They look similar and are not interchangeable.

grade <- function(x) {
  if (x < 10) {
    "single digit"
  } else if (x < 100) {
    "double digits"
  } else {
    "large"
  }
}

vals <- c(7L, 42L, 512L)
for (i in seq_along(vals)) {
  cat(sprintf("%3d -> %s\n", vals[i], grade(vals[i])))
}

band <- ifelse(vals < 10, "single digit",
        ifelse(vals < 100, "double digits", "large"))
cat(sprintf("ifelse : %s\n", paste(band, collapse = ", ")))

Output:

  7 -> single digit
 42 -> double digits
512 -> large
ifelse : single digit, double digits, large

Note that grade has no return statement. An R function returns the value of its last evaluated expression, and an if/else chain is an expression, so each branch's string is the function's value. The loop then calls grade once per element; the ifelse below it produces the same three answers in a single pass without ever seeing an individual element.

while re-tests its condition before every pass and repeat has no condition at all, so it must be broken out of explicitly.

count <- 0L
total <- 0L
while (total < 20L) {
  count <- count + 1L
  total <- total + count
  cat(sprintf("step %d  total %2d\n", count, total))
}

n <- 0L
repeat {
  n <- n + 3L
  if (n %% 4L == 0L) break
}
cat(sprintf("first multiple of 3 divisible by 4 : %d\n", n))

Output:

step 1  total  1
step 2  total  3
step 3  total  6
step 4  total 10
step 5  total 15
step 6  total 21
first multiple of 3 divisible by 4 : 12

The while loop runs a sixth time because the test happens before the body: after five passes the total is 15, which is still under 20, so the sixth pass runs and pushes it to 21. A loop bound written as "stop when the total reaches 20" will always overshoot in exactly this way, and the overshoot is the correct behaviour rather than an off-by-one error. repeat is the right choice when the exit condition can only be evaluated part way through the body.


Technical Depth: One Value, Many Values, and What a Loop Costs

The length-one rule

Every control-flow construct in R has a fixed expectation about how long its condition is, and most bugs in this area are a mismatch between that expectation and what the data actually supplies.

ConstructCondition it expectsReturns
if (cond)exactly one non-NA logicalthe value of the branch taken
ifelse(test, yes, no)a logical vector of any lengtha vector as long as test
the two-character AND and ORone value per side, short-circuitinga single logical
the one-character AND and ORvectors of any length, no short-circuita logical vector
switch(x, ...)one string or one integerthe matching arm, else invisible NULL
for (i in v)not a condition; iterates over vinvisible NULL
while (cond)exactly one logical, re-tested each passinvisible NULL

The two-character forms are && and ||; the one-character forms are & and |. The short-circuiting pair is what belongs inside an if, because it stops as soon as the answer is settled and never evaluates the right-hand side unnecessarily. The vectorised pair is what belongs inside a subsetting expression, because it produces one answer per element.

v <- c(TRUE, FALSE, TRUE)

bad <- try(if (v) "yes" else "no", silent = TRUE)
cat(sprintf("%-22s : %s\n", "if on a vector errored", inherits(bad, "try-error")))
cat(sprintf("%-22s : %s, %s\n", "any(v), all(v)", any(v), all(v)))
cat(sprintf("%-22s : %s\n", "ifelse on a vector",
            paste(ifelse(v, "yes", "no"), collapse = " ")))

reached <- 0L
peek <- function() { reached <<- reached + 1L; TRUE }
cat(sprintf("%-22s : %s\n", "short circuit result", FALSE && peek()))
cat(sprintf("%-22s : %d\n", "short circuit calls", reached))
cat(sprintf("%-22s : %s\n", "vector and",
            paste(v & c(TRUE, TRUE, FALSE), collapse = " ")))

Output:

if on a vector errored : TRUE
any(v), all(v)         : TRUE, FALSE
ifelse on a vector     : yes no yes
short circuit result   : FALSE
short circuit calls    : 0
vector and             : TRUE FALSE FALSE

That first line is version-dependent and worth knowing precisely. From R 4.2 onwards, if on a condition of length greater than one is an error. Before that it silently used the first element, which meant a filter that quietly examined only row one and applied its verdict to the whole data set -- a bug that could sit in production for years. The short circuit calls : 0 line shows the other half of the pair: peek was never called, because FALSE && had already settled the answer.

ifelse stamps the whole belt

ifelse does not choose a branch and then run it. It runs both branches over the entire input and then selects elementwise from the two results.

calls <- 0L
doubled <- function(v) { calls <<- calls + 1L; v * 2L }

x <- c(1L, 2L, 3L, 4L)
picked <- ifelse(x %% 2L == 0L, doubled(x), x)

cat(sprintf("%-16s: %s\n", "picked", paste(picked, collapse = " ")))
cat(sprintf("%-16s: %d\n", "branch calls", calls))
cat(sprintf("%-16s: %d\n", "length in", length(x)))
cat(sprintf("%-16s: %d\n", "length out", length(picked)))

clipped <- ifelse(c(TRUE, FALSE), c("a", "b", "c"), "z")
cat(sprintf("%-16s: %s\n", "shape follows", paste(clipped, collapse = " ")))
cat(sprintf("%-16s: %d\n", "discarded", 3L - length(clipped)))

Output:

picked          : 1 4 3 8
branch calls    : 1
length in       : 4
length out      : 4
shape follows   : a z
discarded       : 1

doubled was called once, not twice and not four times: it received the whole vector x and returned 2 4 6 8, of which only positions 2 and 4 survived the selection. If that branch had been sqrt(x) on a vector containing a negative number, the square root of the negative number would still have been computed, and the resulting warning would still have been raised, even though the answer was thrown away. The shape follows line makes the second rule concrete: the result is as long as test, so a two-element test against a three-element yes silently discards the third value. Nothing warns.

Iterating over the wrong thing

1:length(x) is the most common loop bound in R and it is wrong whenever x can be empty, because the colon operator counts downwards when its right operand is smaller than its left.

empty <- integer(0)
cat(sprintf("%-17s: %s\n", "1:length(empty)", paste(1:length(empty), collapse = " ")))
cat(sprintf("%-17s: %d\n", "seq_along length", length(seq_along(empty))))

visits <- 0L
for (i in 1:length(empty)) visits <- visits + 1L
cat(sprintf("%-17s: %d\n", "bad loop passes", visits))

visits <- 0L
for (i in seq_along(empty)) visits <- visits + 1L
cat(sprintf("%-17s: %d\n", "good loop passes", visits))

Output:

1:length(empty)  : 1 0
seq_along length : 0
bad loop passes  : 2
good loop passes : 0

1:0 is the two-element vector 1 0, so the loop body runs twice on an empty input, once with an index that does not exist and once with index zero, which in R silently returns a zero-length slice rather than erroring. seq_along and seq_len both return integer(0) for empty input and the loop correctly does nothing. Prefer seq_along(x) for indices into x and seq_len(n) when you have a count; the substitution has no downside.

Growing an object versus filling one

Each c(acc, new) allocates a fresh vector and copies the whole accumulator into it, so a loop that grows its result does quadratic work in the number of iterations. Preallocating and assigning by index does linear work. The difference does not show up on six elements and dominates on six hundred thousand.

n <- 6L

grown <- c()
for (i in seq_len(n)) grown <- c(grown, i^2)

filled <- integer(n)
for (i in seq_len(n)) filled[i] <- i * i

mapped <- vapply(seq_len(n), function(i) i * i, integer(1))

cat(sprintf("%-23s: %s\n", "grown", paste(grown, collapse = " ")))
cat(sprintf("%-23s: %s\n", "filled", paste(filled, collapse = " ")))
cat(sprintf("%-23s: %s\n", "mapped", paste(mapped, collapse = " ")))
cat(sprintf("%-23s: %s\n", "identical filled/mapped", identical(filled, mapped)))
cat(sprintf("%-23s: %s\n", "identical grown/filled", identical(grown, filled)))
cat(sprintf("%-23s: %s\n", "grown class", class(grown)))
cat(sprintf("%-23s: %s\n", "filled class", class(filled)))

Output:

grown                  : 1 4 9 16 25 36
filled                 : 1 4 9 16 25 36
mapped                 : 1 4 9 16 25 36
identical filled/mapped: TRUE
identical grown/filled : FALSE
grown class            : numeric
filled class           : integer

All three print the same six numbers and only two of them are the same object. i^2 returns a double because ^ always does, while i * i on two integers stays an integer, so grown is a numeric vector and filled is an integer one. identical sees through the printing and says so. That is worth internalising: in R, 2 and 2L print identically, compare equal under ==, and are not the same type, which is exactly how a column silently becomes a double after one careless arithmetic step.

switch, next, and break

switch replaces a long else if ladder when the test is equality against a single string. Its last unnamed argument is the default.

route <- function(code) {
  switch(code,
    "A" = "airmail",
    "B" = "surface",
    "C" = "courier",
    "unrouted")
}

for (code in c("A", "C", "Z")) {
  cat(sprintf("%s -> %s\n", code, route(code)))
}

kept <- integer(0)
for (i in 1:10) {
  if (i %% 3L == 0L) next
  if (i > 8L) break
  kept <- c(kept, i)
}
cat(sprintf("kept : %s\n", paste(kept, collapse = " ")))

Output:

A -> airmail
C -> courier
Z -> unrouted
kept : 1 2 4 5 7 8

Read the second loop carefully, because the order of the two guards decides where it stops. At i of 9 the next fires first, so the break test is never reached on that pass and the loop survives to i of 10, where it finally breaks. Swap the two lines and the loop stops at 9 instead. next and break make a loop's exit depend on statement order in a way a vectorised expression never does.


Real World Example: A Sorting Office Shift Log

The office belt feeds four chutes, one per delivery zone, and each chute holds three parcels before it has to be wheeled away. Anything over five kilos goes to the manual bench regardless of zone. The shift log has to show where every parcel actually went, which means the program has to know how full each chute was at the moment that parcel arrived -- and that is state carried forward from one parcel to the next, which no vectorised expression can express. This is the case where a loop is the right answer.

parcels <- data.frame(
  id   = c("P01", "P02", "P03", "P04", "P05", "P06",
           "P07", "P08", "P09", "P10", "P11"),
  zone = c("NORTH", "SOUTH", "NORTH", "EAST", "NORTH", "SOUTH",
           "NORTH", "EAST", "WEST", "SOUTH", "WEST"),
  kg   = c(1.2, 4.8, 0.4, 9.5, 2.1, 0.9, 3.3, 0.6, 12.0, 2.5, 0.7),
  stringsAsFactors = FALSE
)

bands <- c("LIGHT", "MEDIUM", "HEAVY")
parcels$band <- bands[findInterval(parcels$kg, c(1, 5)) + 1L]

CAP    <- 3L
chutes <- c("C1", "C2", "C3", "C4", "MANUAL", "OVERFLOW")
used   <- setNames(integer(length(chutes)), chutes)
mass   <- setNames(numeric(length(chutes)), chutes)

parcels$chute <- character(nrow(parcels))
parcels$note  <- character(nrow(parcels))
parcels$dflt  <- logical(nrow(parcels))

for (i in seq_len(nrow(parcels))) {
  z <- parcels$zone[i]
  target <- switch(z, NORTH = "C1", SOUTH = "C2", EAST = "C3", "C4")
  parcels$dflt[i] <- !(z %in% c("NORTH", "SOUTH", "EAST"))

  if (parcels$band[i] == "HEAVY") {
    target <- "MANUAL"
    parcels$note[i] <- "hand carry"
  } else if (used[[target]] >= CAP) {
    target <- "OVERFLOW"
    parcels$note[i] <- "chute full"
  } else {
    parcels$note[i] <- "-"
  }

  used[[target]] <- used[[target]] + 1L
  mass[[target]] <- mass[[target]] + parcels$kg[i]
  parcels$chute[i] <- target
}

hdr  <- "%-7s%-7s%6s%8s%10s%12s\n"
rowf <- "%-7s%-7s%6.1f%8s%10s%12s\n"
rule <- strrep("-", 50)

cat(sprintf(hdr, "PARCEL", "ZONE", "KG", "BAND", "CHUTE", "NOTE"))
cat(rule, "\n", sep = "")
for (i in seq_len(nrow(parcels))) {
  cat(sprintf(rowf, parcels$id[i], parcels$zone[i], parcels$kg[i],
              parcels$band[i], parcels$chute[i], parcels$note[i]))
}
cat(rule, "\n", sep = "")
cat(sprintf("%-14s%6.1f\n", "TOTAL", sum(parcels$kg)))

cat("\n")
cat(sprintf("%-10s%9s%8s\n", "CHUTE", "COUNT", "KG"))
for (ch in chutes) {
  cat(sprintf("%-10s%9d%8.1f\n", ch, used[[ch]], mass[[ch]]))
}

cat("\n")
cat(sprintf("%-9s%6s\n", "BAND", "COUNT"))
for (b in bands) {
  cat(sprintf("%-9s%6d\n", b, sum(parcels$band == b)))
}

cat("\n")
cat(sprintf("%-18s: %d\n", "parcels", nrow(parcels)))
cat(sprintf("%-18s: %s\n", "kg reconciles",
            isTRUE(all.equal(sum(parcels$kg), sum(mass)))))
cat(sprintf("%-18s: %s\n", "overflowed",
            paste(parcels$id[parcels$chute == "OVERFLOW"], collapse = ", ")))
cat(sprintf("%-18s: %s\n", "manual handling",
            paste(parcels$id[parcels$chute == "MANUAL"], collapse = ", ")))
cat(sprintf("%-18s: %s\n", "default arm used",
            paste(parcels$id[parcels$dflt], collapse = ", ")))

Output:

PARCEL ZONE       KG    BAND     CHUTE        NOTE
--------------------------------------------------
P01    NORTH     1.2  MEDIUM        C1           -
P02    SOUTH     4.8  MEDIUM        C2           -
P03    NORTH     0.4   LIGHT        C1           -
P04    EAST      9.5   HEAVY    MANUAL  hand carry
P05    NORTH     2.1  MEDIUM        C1           -
P06    SOUTH     0.9   LIGHT        C2           -
P07    NORTH     3.3  MEDIUM  OVERFLOW  chute full
P08    EAST      0.6   LIGHT        C3           -
P09    WEST     12.0   HEAVY    MANUAL  hand carry
P10    SOUTH     2.5  MEDIUM        C2           -
P11    WEST      0.7   LIGHT        C4           -
--------------------------------------------------
TOTAL           38.0

CHUTE         COUNT      KG
C1                3     3.7
C2                3     8.2
C3                1     0.6
C4                1     0.7
MANUAL            2    21.5
OVERFLOW          1     3.3

BAND      COUNT
LIGHT         4
MEDIUM        5
HEAVY         2

parcels           : 11
kg reconciles     : TRUE
overflowed        : P07
manual handling   : P04, P09
default arm used  : P09, P11

The program splits cleanly along the line the analogy draws. Weight banding is a stamping-head job: one rule, applied to every parcel independently, expressed as a single findInterval call with no loop anywhere. Routing is a lever job, and it is a lever job for a specific reason -- the answer for P07 depends on the three parcels that went into C1 before it. Change the arrival order and P07 goes to C1 while some other NORTH parcel overflows. State that carries forward is the one thing vectorisation cannot express, and it is the only defensible reason to write a for loop over rows in R.

findInterval(kg, c(1, 5)) returns 0 below one, 1 from one up to but not including five, and 2 from five upwards, so adding one indexes straight into bands. Note that this is left-closed, the exact opposite of cut, whose intervals are right-closed by default; the two functions solve the same problem with opposite boundary conventions and mixing them up shifts every edge case by one band. The switch handles zone lookup with its final unnamed argument acting as the default, and parcels$dflt records whether that default fired. It reads TRUE for both WEST parcels, including P09, which shows that the default arm was consulted first and the HEAVY override replaced its answer afterwards.

The two accumulators are named vectors created with setNames, which gives a small fixed-size lookup that reads like a dictionary. used[[target]] uses double brackets deliberately: single brackets on a named vector return a named vector of length one, and the name tags along into every subsequent arithmetic result until something eventually prints with a stray label attached. The final block reconciles the total kilos against the sum of the per-chute kilos through all.equal, which catches a parcel counted into a chute but not added to its mass.

Now the limits. The most serious flaw is that the capacity rule only ever considers the parcel's own zone chute. A NORTH parcel arriving to a full C1 is sent straight to OVERFLOW while C3 sits at one of three and C4 at one of three, so the office reports congestion it does not have. Worse, OVERFLOW is itself unguarded -- the else if protects only the four named chutes -- so it can grow without limit and the report will print OVERFLOW 40 while every real chute shows spare space. Second, HEAVY parcels bypass the capacity check entirely, so a shift of heavy freight reports no overflow at all while the manual bench is buried; the bench needs a cap and a note of its own. Third, the band boundaries at exactly 1.0 and 5.0 kilos are never exercised by this data, so the one part of the rule most likely to be specified wrong is also the only part with no evidence behind it. Fourth, the whole result is a function of row order and nothing in the program says so: no sort, no assertion, no recorded arrival time. Re-read the same parcels in a different order and a different parcel overflows, while every total on the sheet still reconciles perfectly.


Common Mistakes

  1. Putting a vector inside if. From R 4.2 this is an error; before it, only the first element was used and the verdict was applied to everything. Collapse the vector deliberately with any or all, or switch to ifelse if you wanted one answer per element.
  1. Using ifelse for a single decision. It builds and discards a whole vector to answer one question, and it returns something the same length as test, so a length-one test gives a length-one answer no matter how long the branches are.
  1. Assuming ifelse only evaluates the branch it needs. Both branches run over the entire input first. An expensive or invalid computation in the losing branch still happens, warnings and all.
  1. Looping with 1:length(x). When x is empty this counts 1 0 and the body runs twice on nothing. Use seq_along(x) or seq_len(n), which yield integer(0) and iterate zero times.
  1. Growing a result with c() or rbind inside a loop. Every pass reallocates and copies, turning linear work into quadratic. Preallocate with integer(n) or vector("list", n) and assign by index.
  1. Using && on vectors. It expects one value per side; recent R versions error rather than silently taking the first element. Reserve && and || for scalar conditions and & and | for elementwise work.
  1. Forgetting that a for loop's variable outlives the loop. After the loop, i is still bound to its last value, and code below that accidentally reads i will run without complaint on stale data.
  1. Expecting switch to error on an unmatched value. With no default arm it returns NULL invisibly, so a typo produces a silent NULL that only fails several lines later. Always supply a final unnamed default.
  1. Writing a loop for work that has no carried state. If each iteration's result depends only on its own input, the loop is a slower, longer spelling of a vectorised expression, and the loop makes the absence of state impossible to see at a glance.

Best Practices

  • Reach for a loop only when one iteration's result depends on an earlier one; if nothing is carried forward, a vectorised expression is shorter, faster and self-documenting.
  • Bound every loop with seq_along or seq_len, never with 1:length(x), so an empty input produces zero passes instead of two wrong ones.
  • Preallocate the result to its final length before the loop and fill it by index, so the allocation happens once rather than once per iteration.
  • Keep && and || for scalar conditions inside if and while, and & and | for elementwise work inside subsetting; the choice is about length, not about style.
  • Give every switch a final unnamed default arm, even if that arm only raises an error, so an unrecognised value announces itself instead of returning an invisible NULL.
  • When a result depends on input order, say so in code: sort the input explicitly on a stated key at the top of the function rather than inheriting whatever order the caller happened to supply.
  • Prefer vapply over sapply, because it declares the type and length of each result and fails loudly when one element does not conform.
  • Test the exact boundary values of every banding rule, and write down whether the intervals are left- or right-closed, because findInterval and cut disagree about that by default.

Practice Exercises

  1. Write classify(x) that returns "low", "mid" or "high" for a numeric vector using one findInterval call and no loop, then prove it handles the exact boundary values by printing the band for a vector that includes both breakpoints.
  1. Take a numeric vector containing one negative number and compute ifelse(x > 0, sqrt(x), 0). Then rewrite it so the square root is never applied to a negative value, and print the two results side by side to show they agree.
  1. Write two functions that build the first n triangular numbers, one growing a vector with c() and one filling a preallocated integer(n). Print both results, their classes, and whether identical considers them the same object.
  1. Rewrite the shift log so that a full chute falls back to the least-loaded chute with space before resorting to OVERFLOW, and cap the manual bench at four parcels. Print the same summary block and state which parcels changed destination.