Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

r - rlang double curly braces within lm() formula

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) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...