-1

In R 4.1 introduced the native forward pipe (|>) that can be used instead of magrittr's %>%. For example,

c(1, 2, 3) |> length()

is a valid syntax in R > 4.1 and will return 3.

magrittr has a collection of aliases. For example, instead of

1 * 2

I can write

1 %>% magrittr::multiply_by(2)

What are the R > 4.1 equivalent to magrittr's aliases?

Raniere Silva
  • 2,527
  • 1
  • 18
  • 34
  • 3
    Most of those listed aliases are not supported on the right hand side of the base R pipe. a general alias for it is to make a anonymous function such as `1 |> (\(.) . * 2)()` with the expression inside the function being anything you want. Note that if you make you [own aliases](https://stackoverflow.com/questions/68847745/not-possible-to-use-special-functions-with-base-pipe-in-r) it does work. – Donald Seinen Aug 06 '22 at 03:48
  • 1
    Also, bear in mind that the two pipes are *not exact equivalents* of each other. See [here](https://stackoverflow.com/questions/67633022/what-are-the-differences-between-rs-new-native-pipe-and-the-magrittr-pipe) for more details. – Limey Aug 06 '22 at 05:59

1 Answers1

3

Such aliases are not provided by base but this works to multiply by 2. The parentheses shown are required.

1:3 |> (`*`)(2)

It is also possible to use magrittr aliases with |>

library(magrittr)
1:3 |> multiply_by(2)

or to define an alias yourself

mult <- function(x, y) x * y
1:3 |> mult(2)

or

mult <- `*`
1:3 |> mult(2)

Another possibility is to find another way of expressing the same calculation. In this case:

1:3 |> sapply(`*`, 2)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341