using non-standard evaluation with formula

丶灬走出姿态 提交于 2019-12-08 13:24:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!