1

我想要一个函数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,gsubformula.

4

1 回答 1

2

这是有用的东西

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)

这似乎有点乱,因为 quosures 基本上也是公式,而您正试图用它们制作一个常规公式。然后new_formula似乎不允许!!扩展。

如果你真的只是对改变左侧感兴趣,这样的事情可能更直接

my_lm <- function(response) {
  newf <- base_formula
  f_lhs(newf) <- get_expr(enquo(response))
  lm(formula = get_expr(newf),
     data = iris)
}
于 2017-10-06T18:50:37.073 回答