mutate and case_when in R
Adding and deriving columns inside a pipeline.
library(dplyr)
cars <- mtcars %>%
mutate(
kpl = mpg * 0.425,
weight_kg = wt * 453.6,
heavy = wt > 3.5,
class = if_else(cyl > 4, "big", "small")
)
only_new <- transmute(mtcars, ratio = mpg / wt)
banded <- mutate(mtcars,
band = case_when(
mpg < 15 ~ "thirsty",
mpg < 25 ~ "average",
TRUE ~ "efficient"
))
How it works
mutateadds columns computed from existing ones.if_elseis a type-safe vectorized conditional.case_whenhandles several conditions in order.
Keywords and builtins used here
case_whenif_elselibrarymutatetransmute
The run, in numbers
- Lines
- 17
- Characters to type
- 304
- Tokens
- 85
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 54 seconds.
Step 4 of 4 in New columns, step 13 of 27 in dplyr.