使用 tidyeval 为 "lm" 编写函数
Programming a function for "lm" using tidyeval
我正在尝试使用 tidyeval(非标准评估)围绕 "lm" 编写一个函数。使用 base R NSE,它有效:
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 应该替换为 !!
。 Hadley's 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可能来自不同的环境。我们需要检查一下。
我们需要检查用户是否没有取消引用 quosures。 lm()
和 co 不支持这些。 quo_expr()
展平所有 quosures 并在发现某些问题时选择性地发出警告。
我正在尝试使用 tidyeval(非标准评估)围绕 "lm" 编写一个函数。使用 base R NSE,它有效:
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 应该替换为 !!
。 Hadley's 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可能来自不同的环境。我们需要检查一下。我们需要检查用户是否没有取消引用 quosures。
lm()
和 co 不支持这些。quo_expr()
展平所有 quosures 并在发现某些问题时选择性地发出警告。