在函数 F 内部,使用 F 的参数作为 update() 的参数
Inside function F, use an argument to F as an argument to update()
我想要一个类似my_lm
的函数,示例如下:
library(rlang)
base_formula <- new_formula(lhs = quote(potato),
rhs = quote(Sepal.Width + Petal.Length))
my_lm <- function(response) {
lm(formula = update(old = base_formula, new = quote(response) ~ . ),
data = iris)
}
my_lm(response = Sepal.Length)
但是我遇到了以下错误:
Error in model.frame.default(formula = update(old = base_formula, new = enquo(response) ~ :
object is not a matrix
我怀疑我在滥用 rlang
,但我似乎无法弄清楚引用、取消引用和公式化的哪种组合可以解决这个问题。
编辑:所需的输出就像我 运行:
lm(formula = Sepal.Length ~ Sepal.Width + Petal.Length,
数据=鸢尾花)
EDIT2:我还应该澄清一下,我对使用 rlang
通过 update
解决此问题的解决方案比使用 paste
的解决方案更感兴趣, gsub
,以及 formula
。
这是有用的东西
base_formula <- new_formula(lhs = quote(potato),
rhs = quote(Sepal.Width + Petal.Length))
my_lm <- function(response) {
newf <- new_formula(get_expr(enquo(response)), quote(.))
lm(formula = update(old = base_formula, new = newf),
data = iris)
}
my_lm(response = Sepal.Length)
这似乎有点乱,因为等式基本上也是公式,而您正试图用它们制作一个常规公式。然后 new_formula
似乎不允许 !!
扩展。
如果你真的只对改变左手边感兴趣,这样的事情可能更直接
my_lm <- function(response) {
newf <- base_formula
f_lhs(newf) <- get_expr(enquo(response))
lm(formula = get_expr(newf),
data = iris)
}
我想要一个类似my_lm
的函数,示例如下:
library(rlang)
base_formula <- new_formula(lhs = quote(potato),
rhs = quote(Sepal.Width + Petal.Length))
my_lm <- function(response) {
lm(formula = update(old = base_formula, new = quote(response) ~ . ),
data = iris)
}
my_lm(response = Sepal.Length)
但是我遇到了以下错误:
Error in model.frame.default(formula = update(old = base_formula, new = enquo(response) ~ :
object is not a matrix
我怀疑我在滥用 rlang
,但我似乎无法弄清楚引用、取消引用和公式化的哪种组合可以解决这个问题。
编辑:所需的输出就像我 运行:
lm(formula = Sepal.Length ~ Sepal.Width + Petal.Length,
数据=鸢尾花)
EDIT2:我还应该澄清一下,我对使用 rlang
通过 update
解决此问题的解决方案比使用 paste
的解决方案更感兴趣, gsub
,以及 formula
。
这是有用的东西
base_formula <- new_formula(lhs = quote(potato),
rhs = quote(Sepal.Width + Petal.Length))
my_lm <- function(response) {
newf <- new_formula(get_expr(enquo(response)), quote(.))
lm(formula = update(old = base_formula, new = newf),
data = iris)
}
my_lm(response = Sepal.Length)
这似乎有点乱,因为等式基本上也是公式,而您正试图用它们制作一个常规公式。然后 new_formula
似乎不允许 !!
扩展。
如果你真的只对改变左手边感兴趣,这样的事情可能更直接
my_lm <- function(response) {
newf <- base_formula
f_lhs(newf) <- get_expr(enquo(response))
lm(formula = get_expr(newf),
data = iris)
}