将公式粘贴在一起 as.formula 解析问题

paste formula together as.formula parse problem

我试图将一个公式粘贴到模型中的 运行,但是当我尝试合并随机效应时,我 运行 遇到了问题。我想单独定义随机效应,然后添加到公式中。

没有as.formula的简单工作示例:

library(INLA)
data(Epil)
head(Epil)
##Define the model
formulae = y ~ Trt + Age + V4 + f(Ind, model = "iid") + f(rand, model = "iid")
formulae
# y ~ Trt + Age + V4 + f(Ind, model = "iid") + f(rand, model = "iid")
#WORKS
result = inla(formulae, family = "poisson", data = Epil, control.predictor = list(compute = TRUE))

现在如果我想让它更灵活,我可以改变模型之间的随机效应但不改变固定效应,我尝试了这样的事情 as.formula:

test_vars = c("Trt",  "Age", "V4")
mm <- quote(
  f(Ind, model = 'iid') + f(rand, model = "iid")
)
mm
formula_2 <- as.formula(paste("y ~", paste(paste(test_vars, collapse = "+"), "+", mm)))
formula_2 #wont work here as expected
# y ~ Trt + Age + V4 + +y ~ Trt + Age + V4 + f(Ind, model = "iid")

formula_2 <- as.formula(paste("y ~", paste(paste(test_vars, collapse = "+"), "+", parse(text = mm))))
formula_2   #missing + f(rand, model = "iid")
# y ~ Trt + Age + V4 + +f(Ind, model = "iid")


result1 = inla(formula_2, family = "poisson", data = Epil, control.predictor = list(compute = TRUE))
identical(result, result1)
#FALSE

formula_2 是错误的,我只是想要一种方法来做类似

的事情
formula_2 <- as.formula(paste("y ~", paste(paste(test_vars, collapse = "+"), "+", mm)))

所需的输出是:

"y ~ Trt + Age + V4 + f(Ind, model = 'iid') + f(rand,model = 'iid')"

#where I can feed it directly into the model call:
result1 = inla(formula_2, family = "poisson", data = Epil, control.predictor = list(compute = TRUE))

我不想直接手动引用 ("f(Ind, model = 'iid') + f(rand, model = 'iid')") 随机效应,因为这掩盖了它的可读性。我认为 parseeval 可能有帮助?

谢谢

我想这会如你所愿

as.formula(paste0("y ~ ", paste(paste(test_vars, collapse="+"), deparse(mm), sep="+")))
# y ~ Trt + Age + V4 + f(Ind, model = "iid") + f(rand, model = "iid")

由于您将公式构建为字符串,我们确实需要将所有内容都作为字符串而不是引用表达式。因此 deparse 将有助于将引用的表达式转换为字符串以便于操作。

与其将 mm 存储为单引号表达式,不如将所需的附加术语存储为表达式集合可能更容易。例如,这将 return 同样的事情

mm <- expression(
  f(Ind, model = 'iid'),
  f(rand, model = "iid")
)
reformulate(c(test_vars, sapply(mm, deparse)), "y")