Max Gordon
Max Gordon

Reputation: 5467

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.

Upvotes: 0

Views: 240

Answers (2)

Parfait
Parfait

Reputation: 107767

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  

Upvotes: 4

Max Gordon
Max Gordon

Reputation: 5467

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.

Upvotes: 2

Related Questions