JAGS, rjags: "Error in file(modfile, "rt") : cannot open the connection"

StackOverflow https://stackoverflow.com/questions/21923955

  •  14-10-2022
  •  | 
  •  

문제

I have recently started working with JAGS and invoking it inside of R. I finally got jags linked to R with the code

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

and got the output

Linked to JAGS 3.4.0
Loaded modules: basemod,bugs

I also saved the JAGS model data in a separate file in the BUG format (like I was taught).

When I tried to run my data through however I keep getting the error messages:

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"

and

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

Is there some crucial step that I am missing?

EDIT: Code for example problem

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:

model {for (i in 1:N) {
        x[i] ~ dnorm(mu, tau)}
    mu ~ dnorm(0, .0001)
    tau <- pow(sigma, -2)
    sigma ~ dunif(0, 100)}
도움이 되었습니까?

해결책

You may not be giving the full path to the model file age_problem.bug. Correcting this path should do the trick, but I usually cat models to a tempfile, like in the following code, which should work fine for you.

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top