我试图通过使用 for 循环来最小化我的 jags 代码。我的原始代码是
data<- list(r1=c(16, 62, 14, 23, 570, 63, 63, 116),
r2=c(10, 66, 20, 27, 522, 31, 31, 95),
n1=c(53, 106, 56, 82, 1012, 201, 201, 2049),
n2=c(53, 107, 94, 82, 1081, 149, 149, 3097))
NS <- length(data$r1)
library(rjags)
library(coda)
ma <- function(o){
out <- "
model{
for(i in 1:NS){
delta[i,1] <- 0
mu[i] ~ dnorm(0, 0.0001)
for(k in 1:2){
r[i,k] ~ dbin(p[i,k], n[i,k])
logit(p[i,k]) <- mu[i] + delta[i,k]
}
delta[i,2] ~ dnorm(lor, prec)
}
lor ~ dnorm(0, 0.0001)
############## 1 inverse Gamma Dist.
tau2 <- 1/prec
taus <- sqrt(1/prec)
prec ~ dgamma(0.1,0.1)
# prec ~ dgamma(0.01,0.01)
# prec ~ dgamma(0.001,0.001)
############## 2 Uniform Dist.
# tau2 <- tau*tau
# prec <- 1/tau2
# taus <- tau
# tau ~ dunif(0, 2)
# tau ~ dunif(0, 5)
# tau ~ dunif(0, 10)
### Transform ln(OR) into OR
OR <- exp ( lor )
}"
return(out)
}
如您所见,我手动运行每个先前的程序,而不是我想在 for 循环中运行它们我的尝试;
# hyper-parameters
IG <- c(a1=0.1, a2=0.01, a3=0.001,b1=0.1, b2=0.01, b3=0.001)
U <- c(a1=0, a2=0, a3=0, b1=2, b2=5, b3=10)
# priors
prior <- data.frame(IG,U)
if (prior == "IG"){
for (i in 1:3){
tau2[i] <- 1/prec[i]
taus[i] <- sqrt(1/prec[i])
prec[i] ~ dgamma(a[i],b[i])}
}
if (prior == "U"){
for (i in 1:3){
tau2[i] <- tau[i]*tau[i]
prec[i] <- 1/tau2[i]
tau[i] ~ dunif(a[i],b[i])}
}
有没有办法在 rjags 中做到这一点,因为我不确定 JAGS 软件中是否有 if 语句。