tidyverse / magrittr

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

Pipe operator for 2+ arguments #215

Open kbodwin opened 4 years ago

kbodwin commented 4 years ago

I recently found myself wishing for a pipe operator that sends 2 objects into the first 2 elements of a function.

Much like how we have purrr::map and purrr::map2, it'd be cool to have a multiples pipe shortcut.

(I know %>>% has been suggested for other purposes already, but I'll use it here for examples as it feels like the natural choice to me.)

Hypothetical use cases:

dat1, dat2, dat3 %>>%
    bind_rows() %>% ...

or, if the plain comma version looks to gnarly or (most likely) is impossible to implement

list(dat1, dat2, dat3) %>>%
    bind_rows() %>% ...

An example where the arguments aren't interchangeable, and an extra argument exists

list(vec, na.rm = TRUE) %>>%
    mean(trim = 0.1)

It's a pretty minor feature but it could allow some cleaner code when multiple arguments are duplicated, like:

vec_opts <- list(vec, na.rm = TRUE) 

vec_opts %>>% mean(trim = 0.1)

vec_opts %>>% median()

It could maybe bring to the forefront differences in near-duplicated code:

aes_1 <- aes(x = mpg, y = cyl)
aes_2 <- aes(x = mpg, y = am)

list(mtcars, aes_1) %>>%
    ggplot() + geom_point()

list(mtcars, aes_2) %>>%
    ggplot() + geom_point()

or even "picking up" arguments along the way:

mtcars %>%
    filter(am == 1) %>%
    list(aes_1) %>>%
    ggplot() + geom_point()

Twitter discussion here, with some ideas and implementations.

If the maintainers were interested in this feature, I'd be willing to poke around at writing it up in the same style as the ordinary pipe. :)