Since R-Version 4.1.0 the pipe |>
is in the stable version. When passing the lhs into an argument other than the first the Examples of the manual show:
mtcars |> subset(cyl == 4) |> (function(d) lm(mpg ~ disp, data = d))()
or when using \(x)
mtcars |> subset(cyl == 4) |> (\(d) lm(mpg ~ disp, data = d))()
Or use PIPEBIND which currently needs to be activated:
Sys.setenv(`_R_USE_PIPEBIND_` = TRUE)
mtcars |> subset(cyl == 4) |> . => lm(mpg ~ disp, data = .)
Instead of |>
also the Bizarro pipe ->.;
could be used like
mtcars |> subset(cyl == 4) ->.; lm(mpg ~ disp, data = .)
As one purpose of pipe notation in R is to allow a nested sequence of calls to be written in a way that may make the sequence of processing steps easier to follow, at least for me, this is also fulfilled by ->.;
. Bizarro pipe is not really a pipe but for me it is currently a welcome alternative to |>
especially in cases when passing the lhs into an argument other than the first. But when using it I get comments not to use it.
So I want to know if the Bizarro pipe has disadvantages which recommends not to use it?
So far I see that it creates or overwrites .
in the environment and
keeps this reference which will force a copy on modification. But when calling a function, with data in the arguments, also a reference to this data is created. And when using a for
loop var
stays after usage.
for(i in iris) {}
tracemem(i) == tracemem(iris[[ncol(iris)]])
#[1] TRUE
Also for performance it shows not much disadvantages:
x <- 42
library(magrittr)
Sys.setenv(`_R_USE_PIPEBIND_` = TRUE)
#Nonsense operation to test Performance
bench::mark(x
, identity(x)
, "x |> identity()" = x |> identity()
, "x |> (\\(y) identity(y))()" = x |> (\(y) identity(y))()
, "x |> . => identity(.)" = x |> . => identity(.)
, "x ->.; identity(.)" = {x ->.; identity(.)}
, x %>% identity
)
# expression min median `itr/sec` mem_alloc `gc/sec` n_itr
# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:byt> <dbl> <int>
#1 x 60.07ns 69.03ns 13997474. 0B 0 10000
#2 identity(x) 486.96ns 541.91ns 1751206. 0B 175. 9999
#3 x |> identity() 481.03ns 528.06ns 1812935. 0B 0 10000
#4 x |> (\(y) identity(y))() 982.08ns 1.08µs 854349. 0B 85.4 9999
#5 x |> . => identity(.) 484.06ns 528.06ns 1815336. 0B 0 10000
#6 x ->.; identity(.) 711.07ns 767.99ns 1238658. 0B 124. 9999
#7 x %>% identity 2.86µs 3.23µs 294945. 0B 59.0 9998