r - 将公式粘贴在一起 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')"
) 随机效果,因为这掩盖了它的可读性。我认为parse
或eval
可能有帮助?
谢谢
解决方案
我认为这会做你想要的
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")
推荐阅读
- express - 使用 Express 的 GraphQL 安全 Web 套接字
- r - 计算数据框中行的长度
- angular - 将时间转换为 24 小时格式并使用 formControlName 获取值并填充值,角度
- python - 如何逐行合并多个csv文件python
- ruby - 左零数有奇怪的结果
- reactjs - 更改 Chart.js 图例文本
- node.js - 使用 Axios 在 Sequelize 上更新请求 (PUT) 超时
- ssl - Hyperledger Fabric 中出现奇怪的错误消息
- javascript - 有没有办法替换网络通知中的默认浏览器徽标?
- jquery - 仅在桌面视图上使用 Sticky Text JQuery