dplyr::recode Why does pipe generate error?

扶醉桌前 提交于 2019-12-18 19:08:48

问题


If I use recode in a pipe, I get an 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')"

If I pull it out of the pipe, it works fine:

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

Any ideas why? I'd like to stay in the pipe if possible.


回答1:


An equivalent of the baseR solution in dplyr is to use it inside mutate:

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

Directly chaining recode after %>% will pass the data frame to recode as the first argument, which doesn't agree with recode's parameters. The first argument .x needs to be a vector; unlike some other dplyr functions recode doesn't use some non-standard evaluation magic to interpret unit as the column with that name in df. Most functions designed for direct use with the pipe have a data frame as their first argument and their output. You can read more about magrittr and how the pipe works here.



来源:https://stackoverflow.com/questions/49328370/dplyrrecode-why-does-pipe-generate-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!