编程使用“LM”功能tidyeval
问题描述:
我想写使用tidyeval(非标准评价)。采用基础R NSE围绕“LM”的功能,它的工作原理:编程使用“LM”功能tidyeval
lm_poly_raw <- function(df, y, x, degree = 1, ...){
lm_formula <-
substitute(expr = y ~ poly(x, degree, raw = TRUE),
env = list(y = substitute(y),
x = substitute(x),
degree = degree))
eval(lm(lm_formula, data = df, ...))
}
lm_poly_raw(mtcars, hp, mpg, degree = 2)
然而,我还没有想出如何使用tidyeval
和rlang
来编写这个函数。我认为substitute
应该被替换为enquo
,并且由!!
来评估。 Hadley的Adv-R中有一些提示,但我无法弄清楚。
答
这里是那种式构造,可能使它的方式在rlang的未来:
f <- function(x, y, flatten = TRUE) {
x <- enquo(x)
y <- enquo(y)
# Environments should be the same
# They could be different if forwarded through dots
env <- get_env(x)
stopifnot(identical(env, get_env(y)))
# Flatten the quosures. This warns the user if nested quosures are
# found. Those are not supported by functions like lm()
if (flatten) {
x <- quo_expr(x, warn = TRUE)
y <- quo_expr(y, warn = TRUE)
}
new_formula(x, y, env = env)
}
# This can be used for unquoting symbols
var <- "cyl"
lm(f(disp, am + (!! sym(var))), data = mtcars)
棘手的部分是:
的LHS和RHS可能来自不同的环境如果通过
...
的不同层次转发。我们需要检查这一点。我们需要检查用户是否没有引用问题。
lm()
和co不支持这些。quo_expr()
展平所有问题,并在发现某些情况时选择发出警告。
+0
谢谢,那就是我一直在寻找的。仍然需要包裹我的头,虽然:) –
为什么要这样做? – Thomas
为了用dplyr函数编程,它对usw tidyeval/rlang很有用,我只想使用一个系统。 Beides,我想向一些Studenten Nse解释,我认为只使用一个系统更容易,更一致。 –
鉴于lm()不使用与dplyr相同的NSE形式,我不认为用rlang打它会有帮助。 – Thomas