问题
I'm creating a package that uses non-standard evaluation to keep track of the meaning of columns. The package passes a data frame among functions, which do various things do the same set of columns. Nonstandard evaluation works great for this:
my_select <- function(df, xcol, ycol) {
new_df <- dplyr::select(df, !!xcol, !!ycol)
new_df
}
my_select(mtcars, quo(wt), quo(mpg))
However, I'd like a function that works with a formula:
my_lm <- function(df, xcol, ycol) {
new_lm <- lm(!!xcol, !!ycol, data=df)
new_lm
}
my_lm(mtcars, quo(wt), quo(mpg)
returns Error in !xcol : invalid argument type
. I've tried all sorts of combinations of quo()
, enquo()
, and !!
, but the basic problem is that I don't know what kind of object lm
needs.
回答1:
You can create a formula by pasting the values of the equation together, then pass the formula to lm
. I'm sure there's a better way to do this, but here's one working approach:
library(rlang)
my_lm <- function(df, xcol, ycol) {
form <- as.formula(paste(ycol, " ~ ", xcol)[2])
my_lm <- lm(form, data=df)
my_lm
}
my_lm(mtcars, quo(wt), quo(mpg))
#>
#> Call:
#> lm(formula = form, data = mtcars)
#>
#> Coefficients:
#> (Intercept) wt
#> 37.285 -5.344
来源:https://stackoverflow.com/questions/46837200/using-non-standard-evaluation-with-formula