JAGS后期计算和ifelse /步

时间:2017-03-21 14:34:18

标签: r if-statement jags

我对JAGS比较陌生,我正在通过R包jagsUI运行它。我正在建立入住率模型,但我希望在我去的时候总结一下结果。所以我有一个0和1的矩阵:

mat1 <- matrix(rbinom(10*10,1,.5),10,10)
y=mat1

我想要运行以下模型:

# Bundle data and summarize data bundle
str( win.data <- list(y = mat1, M = nrow(mat1), T = ncol(mat1)) )

# Specify model in BUGS language
sink("model.txt")
cat("
model {
# Priors
   psi0 ~ dunif(0, 1)
   p ~ dunif(0, 1)
for(t in 1:(T-1)){
  rho[t] ~ dunif(-1,1)
}
beta0 ~ dnorm(0, 0.1)
# Likelihood
   for (i in 1:M) {    # Loop over sites
      z[i,1] ~ dbern(psi0)         # State model

      y[i,1] ~ dbern(z[i,1]*p)
      for (j in 2:T) {    # Loop over replicate surveys
          logit(psi[i,j])<- beta0 + rho[j-1]*z[i,j-1]
          z[i,j] ~ dbern(psi[i,j])
          y[i,j] ~ dbern(z[i,j]*p)  # Observation model
       }
   }
# Derived quantities
    coln[i,j] <- ifelse(z[i,j]-z[i,j-1]==1,1,0) # colonized
    ext[i,j] <- ifelse(z[i,j-1]-z[i,j]==1,1,0) # went extinct
    tot.coln[,j] <- sum(coln[,j]) # sum of colonized each survey
    tot.ext[,j] <- sum(ext[,j]) # sum of extinctions each survey
    Nocc[,j] <-  sum(z[,j]) # total sites occupied each survey
    coln.rate[,j] <- tot.coln[,j]/Nocc[,j]
    ext.rate[,j] <- tot.ext[,j]/Nocc[,j]

}
",fill = TRUE)
sink()

# Initial values
zst <- apply(y, 1, max, na.rm=TRUE)       # Avoid data/model/inits conflict

y<- as.matrix(y)
zst<- y

inits <- function(){list(z = zst)}

# Parameters monitored
params <- c("psi0", "p", "beta0", "coln.rate", "ext.rate")

# MCMC settings
ni <- 2000   ;   nt <- 1   ;   nb <- 1000   ;   nc <- 3

# Call JAGS and summarize posteriors
library(jagsUI)
fm <- jags(win.data, inits, params, "model.txt", n.chains = nc,
           n.thin = nt, n.iter = ni, n.burnin = nb)
print(fm, dig = 3)

除“#Derived quantity”之后的作品外,模型运行。基本上我想计算每次调查中从0到1和从1到0的变化率。关于它为什么不起作用我的一些想法。 1)z [i,j]不是真正的0和1。 2)计算不应低于派生数量。 3)JAGS手册中的ifelse没有按照我的想法进行。

我还尝试使用“步骤”功能替换衍生数量后的前两行:

coln[i,j] <- step(z[i,j]-z[i,j-1]-0.5) # colonized
ext[i,j] <- step(z[i,j-1]-z[i,j]-0.5) # went extinct

但那里没有运气。有任何想法吗?

1 个答案:

答案 0 :(得分:1)

您正在为ij编制索引,而不会在其中循环。要使其工作,您需要在另一个嵌套的for循环中进行设置。此外,您的灭绝计算不正确。

for(j in 2:T){
    for(i in 1:M){
    coln[i,j-1] <- ifelse(z[i,j]-z[i,j-1]==1,1,0) # colonized
    ext[i,j-1] <- ifelse(z[i,j]-z[i,j-1]==-1,1,0) # went extinct
}
    tot.coln[j-1] <- sum(coln[,j-1]) # sum of colonized each survey
    tot.ext[j-1] <- sum(ext[,j-1]) # sum of extinctions each survey
    Nocc[j-1] <-  sum(z[,j-1]) # total sites occupied each survey
    coln.rate[j-1] <- tot.coln[j-1]/Nocc[j-1]
    ext.rate[j-1] <- tot.ext[j-1]/Nocc[j-1]
}