我试图使用tidyeval (非标准评估).Using基base编写一个围绕"lm“的函数,它的工作原理是:
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,而eval应该由!!代替。在哈德利的Adv中有一些暗示,但我想不出来。
发布于 2017-10-22 08:58:44
下面是将来可能在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()会把所有的商号都压平,如果发现了这些商号,还会发出警告。https://stackoverflow.com/questions/46867888
复制相似问题