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

Time:05-26

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.

CodePudding user response:

As of R 4.2.0, with the forward pipe, you can now use the underscore placeholder (counterpart to magrittr's dot) to pipe object to a selected, named argument:

In a forward pipe |> expression it is now possible to use a named argument with the placeholder _ in the rhs call to specify where the lhs is to be inserted. The placeholder can only appear once on the rhs.

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

Call:
lm(formula = mpg ~ hp, data = mtcars)

Coefficients:
(Intercept)           hp  
   30.09886     -0.06823  

CodePudding user response:

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.

  • Related