3

In my package, I would like magrittr's pipe %>% to have the same behaviour as the native pipe |>, because I work on expressions and calls, and replacing . in an expression is quite challenging.

I tried to create the following function

`%>%` <- function(...){
    `|>`(...)
}

Unfortunately that does not work (function "|>" not found). I wanted to investigate a little further to understand what native pipe |> is and print the code.

> magrittr::`%>%`
function (lhs, rhs) 
{
    lhs <- substitute(lhs)
    rhs <- substitute(rhs)
    kind <- 1L
    env <- parent.frame()
    lazy <- TRUE
    .External2(magrittr_pipe)
}
<bytecode: 0x55a4bb334560>
<environment: namespace:magrittr>


> `|>`
Error: object '|>' not found

> exists("|>")
[1] FALSE

I'm confused: even special functions such as if do exist. If native pipe does not exist, what is it?

Kevin Zarca
  • 2,572
  • 1
  • 18
  • 18
  • 1
    When the R tokenizer comes across a `|>` symbol, the expression to which it belongs is directly parsed as the functional equivalent. For example `substitute(1:10 |> mean())` will return `mean(1:10)`, unlike the magrittr pipe, which will return `1:10 %>% mean()`. The `|>` operator is therefore not a _symbol_ in the same way that other functions (even primitives like `if`) are. It is parsed away by the interpreter as if it never existed. – Allan Cameron Dec 13 '22 at 14:05
  • I'm going to close as a duplicate because the linked question has several good answers that should clarify things. If you get stuck on how to take this information and use it to implement something you are working on, please edit this question and ping me to re-open, or ask a another question. – Allan Cameron Dec 13 '22 at 14:07
  • OK, I get it, it was not obvious for me what "functional composition" meant in the linked question. – Kevin Zarca Dec 13 '22 at 14:53
  • I think yours is a good question, and highlights a different aspect of the native pipe operator. I found myself in the unusual position of upvoting _and_ voting to close your question. I just think it is too similar to the other question to get better answers, and it's good to consolidate all the knowledge on a single page if that makes sense. – Allan Cameron Dec 13 '22 at 15:05
  • Yeah, the `|>` isn't a "think" in R. It gets rewritten automatically when R parses your code (which is why it can run faster). Compare `quote(1:3 |> sum())` to `quote(1:3 %>% sum())`. The `|>` is basically syntactic sugar for creating a completely different expression. It is not a function itself. – MrFlick Dec 13 '22 at 15:17

0 Answers0