Search code examples
rmagrittr

Why isn't the magrittr %<>% assignment pipe working with R's native pipe (|>)


I've noticed that search-replace %>% with |> does induce some errors. The obvious one is the lack of a place-holder, i.e.

mtcars %>%
  lm(mpg ~ hp, data = .)

has to be rewritten into:

mtcars |> 
  (\(d) lm(mpg ~ hp, data = d))()

another thing that appears is that %<>% suddenly fails to work as expected.


Solution

  • The reason that the assignment pipe, %<>% is no longer is due operator precedence. The %<>% occurs before the |>, see below eacmple:

    library(magrittr)
    library(tidyverse)
    
    a <- tibble(a = 1:3)
    a %<>% 
       mutate(b = a * 2) |> 
       mutate(c = a * 3) |> 
       filter(a <= 2)
    a
    

    Returns

    # A tibble: 3 × 2
          a     b
      <int> <dbl>
    1     1     2
    2     2     4
    3     3     6
    

    Thus the

    a %<>% 
      mutate(b = a * 2)
    

    Is the only section that was saved. You can also get a feeling that this may be the case as you get the intended table printed instead which should never be the case with a tibble assignment.