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
- The first matching condition wins, so order the branches.
.defaultcatches the rest; without it you get NA.if_elseis the two-branch, type-strict version of ifelse.
Keywords and builtins used here
ccase_whencutif_elselibrarymutateprinttibble
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.
Step 2 of 4 in New columns, step 11 of 27 in dplyr.