Search code examples
rjags

How to make the contents of a character vector appear like a file in R?


jags.model expects a file name containing a BUGS model as its first argument. In order to contain everything in one script, I sometimes use the writeLines command to write the BUGS model to a file. E.g.,

library(rjags)
writeLines("
model {
    for (i in 1:length(Y1)) {
        Y1[i] ~ dnorm(Beta0, Beta1)
    }
    Beta0 ~ dunif(1, 5)
    Beta1 ~ dunif(0, 10000)
}
"
, "m1.jags")

mod1 <- jags.model("m1.jags", data=Data)

However, if I had my choice, I don't really want the file to be created.

Is there a way of creating some kind of virtual file in R that contains the text?

I was thinking there might be some way of writing the string to a variable using R connections in some way to mimic features of a file.

The rough pseudo code of what I was thinking:

m1.jags <- "model {
        ...
    }
    "
jags.model(SomeRCommand(m1.jags), data=Data)

Solution

  • Thank you @Andrie for telling me the answer: i.e., just surround the character variable with the textConnection function.

    For the sake of completeness, here is how this applied to my specific problem:

    m1.jags <- "
    model {
        for (i in 1:length(Y1)) {
            Y1[i] ~ dnorm(Beta0, Beta1)
        }
        Beta0 ~ dunif(1, 5)
        Beta1 ~ dunif(0, 10000)
    }
    "
    , "m1.jags")
    
    mod1 <- jags.model(textConnection(m1.jags), data=Data)