对公式使用非标准评估 [英] using non-standard evaluation with formula

查看:90
本文介绍了对公式使用非标准评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建使用非标准的软件包评估以跟踪列的含义.程序包在函数之间传递数据帧,这些函数执行各种操作来处理同一组列.非标准评估对此非常有用:

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)

返回Error in !xcol : invalid argument type.我已经尝试过quo()enquo()!!的各种组合,但是基本的问题是我不知道lm需要什么样的对象.

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.

推荐答案

您可以通过将公式的值粘贴在一起来创建公式,然后将该公式传递给lm.我敢肯定有更好的方法可以做到这一点,但这是一种可行的方法:

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

这篇关于对公式使用非标准评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆