首页 > 解决方案 > 将公式粘贴在一起 as.formula 解析问题

问题描述

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

没有的简单工作示例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可能有帮助?

谢谢

标签: rparsingevalpasterandom-effects

解决方案


我认为这会做你想要的

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为单引号表达式,不如将所需的附加术语存储为表达式集合,这可能会更容易。例如,这将返回相同的东西

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

推荐阅读