typestar

case_when and if_else in R

Vectorized conditionals, evaluated in order.

library(dplyr)

runs <- tibble(tpm = c(104, 96, 88, 60, NA))

print(mutate(runs,
             stars = case_when(
               is.na(tpm) ~ 0L,
               tpm >= 100 ~ 3L,
               tpm >= 90 ~ 2L,
               .default = 1L
             ),
             fast = if_else(tpm > 90, "yes", "no", missing = "unknown")))

print(mutate(runs, band = cut(tpm, breaks = c(0, 90, 100, Inf),
                              labels = c("slow", "good", "fast"))))

How it works

  1. The first matching condition wins, so order the branches.
  2. .default catches the rest; without it you get NA.
  3. if_else is the two-branch, type-strict version of ifelse.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
330
Tokens
119
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 75 seconds.

Type this snippet

Step 2 of 4 in New columns, step 11 of 27 in dplyr.

← Previous Next →