Search code examples
rdplyrtype-conversionmagrittr

Factor to numeric conversion via %>%: unexpected results


When converting a factor into numeric vector via the pipe %>% operator, I have wrongly assumed that

myfactor %>% as.character %>% as.numeric

would give the same result as

myfactor %>% as.numeric(as.character(.))

c(0,1,2) %>% as.factor  %>% as.character %>% as.numeric ## returns 0,1,2
c(0,1,2) %>% as.numeric(as.character(as.factor(.)))     ## returns 0,1,2
c(0,1,2) %>% as.factor  %>% as.numeric(as.character(.)) ## returns 1,2,3 (unexpected)
myfun <- function(x) as.numeric(as.character(x))
c(0,1,2) %>% as.factor  %>% myfun                       ## returns 0,1,2

Could someone kindly explain the discrepant results? Thank you!


Solution

  • The pipe operator passes the piped object as first argument of the following function. The dot only changes this behavior when it is in the same function call, this is explained in the documentation in the details section.

    So your third line is equivalent to

    as.numeric(as.factor(c(0,1,2)), as.character(as.factor(c(0,1,2))))
    

    while to get the expected result you would need

    c(0,1,2) %>% as.factor %>% { as.numeric(as.character(.)) }