typestar

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

  1. mutate adds columns computed from existing ones.
  2. if_else is a type-safe vectorized conditional.
  3. case_when handles several conditions in order.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in New columns, step 13 of 27 in dplyr.

← Previous Next →