合并 mutate_at 和 case_when

combining mutate_at with case_when

我要改造以下代码:

labels = 'x'
dataX <- data.frame(x = colors())
special <- sample(colors(),5)
dataX <- dataX %>% mutate("names2" := dplyr::case_when(UQ(sym(labels)) %in% special ~ UQ(sym(labels))))

进入一些没有 := 也能工作的代码,因为这在 运行 包检查时给了我一个注释。

因此我尝试使用 mutate_at 但不能将它与 case_when 结合使用:

dataX <- dataX %>% mutate_at(c("names3" = labels) , funs(dplyr::case_when(.) %in% special ~ .))

失败:

Error in mutate_impl(.data, dots) : 
  Column `names3` is of unsupported type quoted call

因此,我的问题。

到目前为止我想到的最好的是:

testx <- function(x, special){tmp <- x %in% special; x[!tmp] <- NA; as.character(x)}
dataX <- dataX %>% mutate_at(c("names4" = labels) , funs(testx(., special)))

我觉得这像是一个语法错误。只需将括号放在正确的位置:

dataX %>%
  mutate_at(c("names3" = labels),
            funs(dplyr::case_when(. %in% special ~ .))) %>% 
  filter(!is.na(names3)) 
#>            x     names2     names3
#> 1     grey41     grey41     grey41
#> 2     grey72     grey72     grey72
#> 3     grey89     grey89     grey89
#> 4 mistyrose4 mistyrose4 mistyrose4
#> 5 steelblue2 steelblue2 steelblue2