# 如何将列标题插入到贝叶斯回归模型 (brm) 的 for 循环中？

##### 问题描述投票：0回答：1

``````dat <- data.frame(y =  rbeta(10, 0.7, 1.5),
x = sample(c(0,1), 10, replace=TRUE),
a1 = abs(rnorm(10)),
a2 = abs(rnorm(10)),
a3 = abs(rnorm(10)),
b1 = abs(rnorm(10)),
b2 = abs(rnorm(10)),
b3 = abs(rnorm(10)))
``````

``````library(brms)

for (i in 1:3){
model <- brm(
formula = bf(
y | weights(paste0("a",i)) ~ x,
phi ~ x + paste0("b",i),
zoi ~ x + paste0("b",i),
coi ~ x + paste0("b",i),
family = zero_one_inflated_beta()
),
data = dat
)
mod <- summary(model)
e[i] <- mod\$fixed["x1", "Estimate"]
}
``````

``Error: The following variables can neither be found in 'data' nor in 'data2':'i' ``

``````data %>% reframe(across(a1:a3,\(a) {
list(summary(brm(
formula = bf(
y | weights(a) ~ x,
phi ~ x + ?,
zoi ~ x + ?,
coi ~ x + ?,
family = zero_one_inflated_beta()
),
data = dat
)))
}))
``````

r loops stan brms
##### 1个回答
0

``as.formula()``
``formula()``
，或者在本例中使用
``reformulate()``
（这并没有什么不同，但我发现更美观）来构建您的公式。

``````ffun <- function(i, response) {
reformulate(c("x", paste0("b", i)), response = response)
}
``````

``````library(brms)
for (i in 1:3) {
model <- brm(
formula = bf(
reformulate("x", response = sprintf("y | weights(a%d)", i)),
ffun(i, "phi"),
ffun(i, "zoi"),
ffun(i, "coi"),
family = zero_one_inflated_beta()
),
data = dat
)
}
``````