我试图将一个公式粘贴到一起,以便在模型中运行,但当我试图将随机效应结合起来时,我遇到了一些问题。我想分别定义随机效应,然后加入公式。
没有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)
#FALSEformula_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')")随机效应,因为这掩盖了它的可读性。我认为parse或eval能帮上忙吗?
谢谢
发布于 2020-08-04 15:26:08
我想这能做你想做的
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")https://stackoverflow.com/questions/63249471
复制相似问题