dplyr::recode 为什么管道会产生错误?

dplyr::recode Why does pipe generate error?

如果我在管道中使用重新编码,我会得到一个错误:

df <-  df %>%
  recode(unit, .missing="g")

Error in UseMethod("recode") : no applicable method for 'recode' applied to an object of class "c('tbl_df', 'tbl', 'data.frame')"

如果我将它从管道中拉出,它会正常工作:

df$unit <- recode(df$unit, .missing="g")

知道为什么吗?如果可能的话,我想留在管道里。

dplyr 中 baseR 解决方案的等效方法是在 mutate:

中使用它
df %>%
    mutate(unit = recode(unit, .missing="g"))

%>%之后直接链接recode会将数据帧作为第一个参数传递给recode,这与recode的参数不一致。第一个参数 .x 需要是一个向量;与其他一些 dplyr 函数不同,recode 不使用某些 non-standard 评估魔法将 unit 解释为 df 中具有该名称的列。大多数设计为直接与管道一起使用的函数都有一个数据框作为它们的第一个参数和它们的输出。您可以阅读有关 magrittr 以及管道工作原理的更多信息 here.