2 years ago
#192110

Claudiu Papasteri
What are the differences between R's new native pipe `|>` and the old native pipe `->.;`?
In R 4.1 a native pipe operator was introduced that is "more streamlined" than previous implementations. See this post about it.
This is a question inspired by the thread "What are the differences between R's new native pipe |> and the magrittr pipe %>%?".
I will leave aside the magritter pipe where a %>% b(...) is most commonly used to denote {. <- a; b(., ...)} (with dot side effects hidden) because it is clearly different.
I found this thread helpful in understanding the |> does "just" functional composition with no discernible overhead.
The old native pipe ->.; is lengthy but works perfectly for functional composition.
The old native pipe ->.; is composed of:
->assignment,.variable,;statement end
Both seem practically the same for usual purposes.
1:3 |> sum()
#> [1] 6
1:3 ->.; sum(.)
#> [1] 6
The old native pipe uses dot placeholder.
mtcars ->.;
lm(mpg ~ disp, data = .)
#>
#> Call:
#> lm(formula = mpg ~ disp, data = .)
#>
#> Coefficients:
#> (Intercept) disp
#> 29.59985 -0.04122
The new native pipe doesn’t have a placeholder.
mtcars |>
lm(mpg ~ disp, data = .)
#> Error in is.data.frame(data): object '.' not found
mtcars |>
lm(mpg ~ disp)
#> Error in as.data.frame.default(data): cannot coerce class '"formula"' to a data.frame
This means you have to do function declaration gymnastics to make it work when you don't want to pipe into the first unnamed argument.
mtcars |>
(function(x) lm(mpg ~ disp, data = x))()
#>
#> Call:
#> lm(formula = mpg ~ disp, data = x)
#>
#> Coefficients:
#> (Intercept) disp
#> 29.59985 -0.04122
mtcars |>
(\(x) lm(mpg ~ disp, data = x))() # alternative new function-creation syntax
#>
#> Call:
#> lm(formula = mpg ~ disp, data = x)
#>
#> Coefficients:
#> (Intercept) disp
#> 29.59985 -0.04122
I really want to understand the new pipe and its utility.
- Are there any useful patterns you found that are facilitated by
|>? - Does the development of
=>operator that is "available but not active" change the prospects for|>? - When needing only functional composition why don't we use the old
pipe
->.;? Why is it so underutilized, while the new|>gets all the love?
I love R and I would like to love its newer developments. This is why I need to understand. Any insightful answers are welcome.
r
magrittr
0 Answers
Your Answer