JAGS,rjags:“文件错误(modfile,”rt“):无法打开连接”

时间:2014-02-21 02:17:14

标签: r jags

我最近开始使用JAGS并在R中调用它。我终于将jags链接到R代码

install.packages("rjags")
library(rjags)

并获得输出

Linked to JAGS 3.4.0
Loaded modules: basemod,bugs

我还将JAGS模型数据保存在BUG格式的单独文件中(就像我教过的那样)。

当我尝试运行数据时,我不断收到错误消息:

Error in file(modfile, "rt") : cannot open the connection
In addition: Warning message:
In file(modfile, "rt") :
  cannot open file 'age_problem.bug': No such file or directory
Error in jags.model("age_problem.bug", data = list(X = X, N = length(X)),  : 
  Cannot open model file "age_problem.bug"

Error in update(jags, 1000) : object 'jags' not found

我缺少一些关键步骤吗?

编辑:代码例如问题

N <- 1000
x <- rnorm(N, 0, 5)

write.table(x,
            file = 'example1.data',
            row.names = FALSE,
            col.names = FALSE)

library('rjags')

jags <- jags.model('example1.bug',
                   data = list('x' = x,
                               'N' = N),
                   n.chains = 4,
                   n.adapt = 100)

update(jags, 1000)

jags.samples(jags,
             c('mu', 'tau'),
             1000)

JAGS模型:

model {for (i in 1:N) {
        x[i] ~ dnorm(mu, tau)}
    mu ~ dnorm(0, .0001)
    tau <- pow(sigma, -2)
    sigma ~ dunif(0, 100)}

1 个答案:

答案 0 :(得分:3)

您可能没有提供模型文件age_problem.bug的完整路径。修正此路径应该可以解决问题,但我通常cat模型为tempfile,就像下面的代码一样,它应该适合您。

library(rjags)
N <- 1000
x <- rnorm(N, 0, 5)

cat('model {for (i in 1:N) {
  x[i] ~ dnorm(mu, tau)}
  mu ~ dnorm(0, .0001)
  tau <- pow(sigma, -2)
  sigma ~ dunif(0, 100)}', file={f <- tempfile()})

jags <- jags.model(f, data = list(x = x, N = N), n.chains = 4, n.adapt = 100)
update(jags, 1000)