在mutate中使用case_when时是否需要数据帧名称?

时间:2016-11-06 01:16:19

标签: 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
  ))

上面的代码会出错:Error in eval(substitute(expr), envir, enclos) : object 'Title' not found

但是,下面的代码有效。 case_when中是否需要数据框名称(使代码更加详细)。

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
  ))

1 个答案:

答案 0 :(得分:3)

我们可以使用.$代替调用full$

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

数据

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