0

I am working through the textbook "Bayesian Ideas and Data Analysis" by Christensen et al.

There is a simple exercise in the book that involves cutting and pasting the following code to run in Winbugs:

model{ y ~ dbin(theta, n) # Model the data 
ytilde ~ dbin(theta, m) # Prediction of future binomial 
theta ~ dbeta(a, b) # The prior 
prob <- step(ytilde - 20) # Pred prob that ytilde >= 20 } 
list(n=100, m=100, y=10, a=1, b=1) # The data 
list(theta=0.5, ytilde=10) # Starting/initial values

I am trying to translate the following into R2jags code and am running into some trouble. I thought I could fairly directly write my R2Jags code in this fashion:

model {
    #Likelihoods
    y ~ dbin(theta,n)
    yt ~ dbin(theta,m)
    #Priors
    theta ~ dbeta(a,b)
    prob <- step(yt - 20)
}

with the R code:

library(R2jags)

n <- 100
m <- 100
y <- 10
a <- 1
b <- 1

jags.data <- list(n = n,
                  m = m,
                  y = y,
                  a = a,
                  b = b)

jags.init <- list(
                 list(theta = 0.5, yt = 10), #Chain 1 init
                 list(theta = 0.5, yt = 10), #Chain 2 init
                 list(theta = 0.5, yt = 10) #Chain 3 init
                 ) 

jags.param <- c("theta", "yt")

jags.fit <- jags.model(data = jags.data,
                     inits = jags.inits,
                     parameters.to.save = jags.param,
                     model.file = "hw21.bug",
                     n.chains = 3,
                     n.iter = 5000,
                     n.burnin = 100)

print(jags.fit)

However, calling the R code brings about the following error:

Error in jags.model(data = jags.data, inits = jags.inits, parameters.to.save = jags.param,  : 
  unused arguments (parameters.to.save = jags.param, model.file = "hw21.bug", n.iter = 5000, n.burnin = 100)

Is it because I am missing a necessary for loop in my R2Jags model code?

4

2 回答 2

2

错误来自 R 函数 jags.model(不是来自 JAGS) - 您试图将参数 parameters.to.save 等用于错误的函数。

如果您希望模型尽可能与 WinBUGS 相似,有一种比在 R 中指定数据和初始值更简单的方法。将以下内容放入工作目录中名为“model.txt”的文本文件中:

model{
  y ~ dbin(theta, n) # Model the data 
  ytilde ~ dbin(theta, m) # Prediction of future binomial 
  theta ~ dbeta(a, b) # The prior 
  prob <- step(ytilde - 20) # Pred prob that ytilde >= 20
} 

data{
  list(n=100, m=100, y=10, a=1, b=1) # The data 
}

inits{
  list(theta=0.5, ytilde=10) # Starting/initial values
}

然后在 R 中运行它:

library('runjags')
results <- run.jags('model.txt', monitor='theta')
results
plot(results)

有关将 WinBUGS 模型转换为 JAGS 的方法的更多信息,请参阅: http ://runjags.sourceforge.net/quickjags.html

马特

于 2017-02-03T17:50:39.690 回答
0

这篇旧博客文章有一个广泛的示例,将 BUGS 转换为通过 package rjagsnot访问的 JAGS R2jags。(我更喜欢这个包runjags。)我知道我们应该在这里提供独立的答案,而不仅仅是链接,但帖子相当长。它遍历脚本的每个逻辑步骤,包括:

  • 加载包
  • 指定模型
  • 组装数据
  • 初始化链
  • 运行链条
  • 检查结果
于 2017-02-03T17:52:15.610 回答