Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is dataframe name required when using case_when inside mutate? [duplicate]

Tags:

r

dplyr

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
  ))
like image 215
Logan Avatar asked Oct 18 '22 23:10

Logan


1 Answers

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'
like image 185
akrun Avatar answered Oct 21 '22 03:10

akrun