tidyverse / magrittr

Improve the readability of R code with the pipe
https://magrittr.tidyverse.org
Other
957 stars 157 forks source link

Question: defining a pipe operator with equivalent behavior to `%>% {...}` #272

Closed ramiromagno closed 2 months ago

ramiromagno commented 2 months ago

Hi!

I know that if the placeholder is only used in a nested function call, the lhs is also placed as the first argument, and we can override this by wrapping the rhs in braces. However, I'm wondering if there's a straightforward way, using magrittr's exported functions, to create a new pipe operator that allows multiple placements but never places the lhs as the first argument.

In other words, would it be easy to define a new pipe, say %>>%, that makes these two commands equivalent?

1:10 %>% {c(min(.), max(.))}
1:10 %>>% c(min(.), max(.))

I'm not suggesting that this functionality should be included in magrittr, as I understand the current design choices are deliberate. I'm just asking if I wanted this functionality in my own code, would it be straightforward to implement using one of the exported functions from magrittr?

Thanks!

lionel- commented 2 months ago

Untested but try something along the lines of:

`%>>%` <- function(data, expr) {
  eval(substitute(expr), list(. = data), parent.frame())
}
ramiromagno commented 2 months ago

Thank you Lionel! This is neat and effective!