fitbugs.R

Jouni wrote a little R program that allows you to write a Bugs model as an R function. His “fitbugs” program then parses the R function and runs Bugs. It’s just a convenience, but it allows you to set up the Bugs model and specify data, parameters, and initial values, all in one place. This is a little more convenient than having to put the Bugs model in a separate file.

Here’s an example:

## Example: this is the bugs model written as an R function:
## Note that the data variables, the list of the variables to save, and
## the list of the variables to initialize are given as comments inside the function.
##

.example.bugs.model <- function () { # data : n, J, y, state, income # param : a, b, mu.a # a = rnorm(J) # b = rnorm(1) # mu.a = rnorm(1) # sigma.y = runif(1) # sigma.a = runif(1) # for (i in 1:n) { y[i] ~ dnorm(y.hat[i], tau.y) y.hat[i] <- a[state[i]] + b*income[i] } b ~ dnorm(0, .0001) tau.y <- pow(sigma.y, -2) sigma.y ~ dunif (0, 100) for (j in 1:J) { a[j] ~ dnorm (mu.a, tau.a) } mu.a ~ dnorm(0, .0001) tau.a <- pow(sigma.a, -2) sigma.a ~ dunif (0, 100) } ## Then, you'd call: ## ## fitbugs(.example.bugs.model) ##

5 thoughts on “fitbugs.R

  1. Hi!

    Jouni, impresive. I also have a convenience function bugsModel() [function,help page] to write and print BUGS model directly in R, however it does not support running BUGS. Since I use character mode the whole thing is very simple and no parsing is done by R. I use this with connection to bugs() in R2WinBUGS package.

  2. This made Andrew Thomas very happy today: he was amusing himself by trying to work out what happens to error messages.

    More seriously: how much of a stretch would it be to get a function that would take an lmer() model specification, and write the BUGS code?

    Bob

  3. fitbugs() writes a short program that calls the function bugs() (from the package R2WinBUGS). To see the error messages, you set the argument debug=TRUE, which prevents the WinBUGS window from closing after WinBUGS is terminated. fitbugs passes the value of "debug" to bugs(), which does the rest.

    So, fitbugs() is just a method to call bugs(), but I've found it convenient since (1) you'll get a rough syntax check for your BUGS model in R and (2) you can keep both the bugs model and the R code in the same file and (3) you don't have to write the code to set up the bugs() function call.

    As for the lmer() => BUGS conversion, that should be easy, but perhaps I'd write the script in perl and call it from within R to execute it.

Comments are closed.