rlang double curly braces within lm() formula
Asked Answered
S

2

5

Is it possible to use the rlang tidy evaluation operator {{ within an lm formula?

I know that you can use the double curly braces to define a general function such as this:

my_scatter <- function(df, xvar, yvar) {
     ggplot(df) +
          geom_point(aes(x = {{xvar}}, y = {{yvar}}))
}

my_scatter(mpg, cty, hwy) 

But I was wondering whether there was a way to make a similar call within formulas such as inside lm():

my_lm <- function(df, yvar, xvar) {
     lm({{yvar}} ~ {{xvar}} , data = df)
}

my_lm(mpg, cty, hwy) 
Shout answered 1/1, 2021 at 6:30 Comment(0)
S
9

A couple of nuances. First, {{ is generally only supported in functions powered by tidyverse. The upcoming rlang::inject() function will allow you to extend that support to arbitrary functions.

Second, {{ is shorthand for !!enquo(), which captures the expression provided to the function AND the environment where that expression should be evaluated. Since the environment is already provided by the data frame df, the better verb to use here is ensym(), which captures the symbol only.

The following works with rlang 0.4.10:

my_lm <- function(df, yvar, xvar) {
    ysym <- rlang::ensym(yvar)
    xsym <- rlang::ensym(xvar)
    rlang::inject( lm(!!ysym ~ !!xsym, data=df) )
}

my_lm(mpg, cty, hwy)
Scissel answered 1/1, 2021 at 17:20 Comment(0)
R
0

lm expects a formula object which you can construct using reformulate/as.formula.

my_lm <- function(df, yvar, xvar) {
  lm(reformulate(xvar, yvar), data = df)
}

my_lm(mpg, 'cty', 'hwy') 
Runesmith answered 1/1, 2021 at 6:39 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.