Logan Logan - 29 days ago 10
R Question

Is dataframe name required when using case_when inside mutate?

full <- full %>%
mutate(Title = case_when(
Title %in% c('Mlle', 'Ms') ~ 'Miss',
Title == 'Mme' ~ 'Mrs',
Title %in% rare_title ~ 'Rare Title',
TRUE ~ Title
))


Code above gives an error:
Error in eval(substitute(expr), envir, enclos) : object 'Title' not found


However, below code works. Is the data-frame name required inside case_when (makes the code more verbose).

full <- full %>%
mutate(Title = case_when(
full$Title %in% c('Mlle', 'Ms') ~ 'Miss',
full$Title == 'Mme' ~ 'Mrs',
full$Title %in% rare_title ~ 'Rare Title',
TRUE ~ full$Title
))

Answer

We can use .$ instead of calling full$

full <- full %>% 
          mutate(Title = case_when(
                 .$Title %in% c('Mlle', 'Ms') ~ 'Miss',
                  .$Title == 'Mme' ~ 'Mrs',
                   .$Title %in% rare_title ~ 'Rare Title',
                    TRUE ~ .$Title
             ))

data

set.seed(24)
full <- data.frame(Title = sample(c('Mlle', 'Ms', 'Mme', 'Colonel', 'Jr'), 20,
                 replace=TRUE), stringsAsFactors= FALSE)
rare_title <- 'Colonel'
Comments