Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr::recode Why does pipe generate error?

Tags:

r

pipe

dplyr

recode

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.

like image 431
datakritter Avatar asked Mar 16 '18 19:03

datakritter


1 Answers

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.

like image 86
Psidom Avatar answered Oct 01 '22 01:10

Psidom