Erez Shomron
2021-Jun-19 08:21 UTC
[Rd] Additional an example for the forward pipe operator's documentation
Hello, While playing around with the new forward pipe operator I've noticed there's a possibly overlooked usage for the operator, which would be very beneficial to document. Whenever you want the LHS to be passed to an argument other than the first, the documented example demonstrates how to do that with an anonymous function. However the syntax is less than ideal (aesthetically): mtcars |> subset(cyl == 4) |> (function(d) lm(mpg ~ disp, data = d))() Fortunately there's a better, undocumented option using named arguments: mtcars |> subset(cyl == 4) |> lm(formula = mpg ~ disp) The reason this works, is because of how R matches arguments. As the language definition states, first named arguments are matched, then partial matching, and only afterwards positional arguments are matched. I think people that are frustrated with former syntax would be happy to know the latter option exists. That's just my opinion. Thank you for reading, Erez
Gabor Grothendieck
2021-Jun-19 12:25 UTC
[Rd] Additional an example for the forward pipe operator's documentation
These also work in this particular case although not in general and the Call: line in the output differs: mtcars |> subset(cyl == 4) |> with(lm(mpg ~ disp)) mtcars |> with(lm(mpg ~ disp, subset = cyl == 4)) On Sat, Jun 19, 2021 at 7:23 AM Erez Shomron <erezshomron at mykolab.com> wrote:> > Hello, > > > While playing around with the new forward pipe operator I've noticed > there's a possibly overlooked usage for the operator, which would be > very beneficial to document. > > Whenever you want the LHS to be passed to an argument other than the > first, the documented example demonstrates how to do that with an > anonymous function. > > > However the syntax is less than ideal (aesthetically): > > > mtcars |> subset(cyl == 4) |> (function(d) lm(mpg ~ disp, data = d))() > > > Fortunately there's a better, undocumented option using named arguments: > > > mtcars |> subset(cyl == 4) |> lm(formula = mpg ~ disp) > > > The reason this works, is because of how R matches arguments. As the > language definition states, first named arguments are matched, then > partial matching, and only afterwards positional arguments are matched. > > > I think people that are frustrated with former syntax would be happy to > know the latter option exists. > > > That's just my opinion. > > > Thank you for reading, > > Erez > > ______________________________________________ > R-devel at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-devel-- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com