mutated variable using case_when() -- am I using it efficiently?

I have mutated adult using case_when(). Am I using case_when() efficiently?

df <- tibble(age = 16:21)
df %>% 
  mutate(adult = case_when(age >= 18 ~ TRUE,
                           age <  18 ~ FALSE)) 
age adult
16 FALSE
17 FALSE
18 TRUE
19 TRUE
20 TRUE
21 TRUE

That's fine.
Though in this example it's potentially overkill. Consider.

df %>% 
  mutate(adult = age>=18)
2 Likes

The other issue is speed if you have to do more than a few. nirgrahamuk's answer takes 9.4 milliseconds while budugulo's answer takes 165.7 ms to run the code.

library(microbenchmark)
df <- tibble(age=sample(16:21, size=1000000, replace=T))
microbenchmark(
df %>%   mutate(adult = case_when(age >= 18 ~ TRUE, age <  18 ~ FALSE)),
df %>%   mutate(adult = age>=18),
times=50)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.