Search code examples
rdplyrmagrittr

dplyr pipe input processing?


I have not been able to find an answer to this question, so I want to pose it here. Does anyone know what is going on here?

as.integer(.29*100)
[1] 28

.29*100 %>% as.integer
[1] 29

I understand that .29*100 would be a double and doubles cannot be perfectly represented, hence why we get that output from as.integer since it just casts the double to an int, but what is it about the pipe which is making the result different?


Solution

  • We need the parens () to keep it as a single block otherwise there is an operator precedence

    library(magrittr)
    (.29 * 100) %>%
          as.integer
    #[1] 28
    

    i.e. it is doing

    as.integer(100) * 0.29
    #[1] 29
    

    We can also do some versions of the above if there is any difficulty in wrapping with parens

    .29 %>%
        `*`(100) %>% 
       as.integer
    #[1] 28
    

    or use the alias multiply_by

    .29 %>%
        multiply_by(100) %>%
       as.integer
    #[1] 28