Native pipe with lm()

The new native pipe operator puts the LHS into the first argument on the RHS. This is a problem when piping data to the lm() function, which expects the formula first, data second. I recently saw an elegant solution in a June blog post by Keith McNulty, which he credits to Matthias Gomolka. It may be widespread knowledge, but it was a revelation to me, so I decided to post it here. It is based on the fact that the native pipe actually puts the LHS into the first unnamed argument. If you want the LHS to appear as the second argument, just include the function's name for the first argument! In the case of lm() you can call it 'formula' or any truncation, even just 'f'.

These are the methods I was using and the only one I am using now.

mtcars |> with(lm(mpg ~ disp + wt)) # works, but drops mtcar's rownames. 
#> 
#> Call:
#> lm(formula = mpg ~ disp + wt)
#> 
#> Coefficients:
#> (Intercept)         disp           wt  
#>    34.96055     -0.01772     -3.35083

mtcars |> {\(d,f) lm(f, d)}(mpg ~ disp + wt)
#> 
#> Call:
#> lm(formula = f, data = d)
#> 
#> Coefficients:
#> (Intercept)         disp           wt  
#>    34.96055     -0.01772     -3.35083

Sys.setenv("_R_USE_PIPEBIND_" = TRUE)
mtcars |> d => lm(mpg ~ disp + wt, d)  # can even use . as the placeholder!
#> 
#> Call:
#> lm(formula = mpg ~ disp + wt, data = mtcars)
#> 
#> Coefficients:
#> (Intercept)         disp           wt  
#>    34.96055     -0.01772     -3.35083

mtcars |> lm(formula = mpg ~ disp + wt) 
#> 
#> Call:
#> lm(formula = mpg ~ disp + wt, data = mtcars)
#> 
#> Coefficients:
#> (Intercept)         disp           wt  
#>    34.96055     -0.01772     -3.35083

Created on 2021-07-24 by the reprex package (v2.0.0)

4 Likes

How is this different from tidyverse's pipe operator %>% ?

Keith McNulty has a good explanation:

https://towardsdatascience.com/the-new-native-pipe-operator-in-r-cbc5fa8a37bd

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.