strange jags.parallel error / avoiding lazy evaluation in function call

1.9k views Asked by At

I have a function call (to jags.parallel) that works when given a numerical argument like n.iter = 100 but fails when the argument uses a variable value, n.iter = n.iter. This looks like it might be a bug in jags.parallel

A minimal reproducible example of the error:

    library(R2jags)
    model.file <- system.file(package="R2jags", "model", "schools.txt")
    J <- 8.0
    y <- c(28.4,7.9,-2.8,6.8,-0.6,0.6,18.0,12.2)
    sd <- c(14.9,10.2,16.3,11.0,9.4,11.4,10.4,17.6)    
    jags.data <- list("y","sd","J")
    jags.params <- c("mu","sigma","theta")
    jags.inits <- function(){
      list("mu"=rnorm(1),"sigma"=runif(1),"theta"=rnorm(J))
    }

Then this works:

    jagsfit.p <- jags.parallel(data=jags.data, inits=jags.inits, jags.params, 
                               n.iter=5000, model.file=model.file)

But this does not:

     n.iter=5000
    jagsfit.p <- jags.parallel(data=jags.data, inits=jags.inits, jags.params,
                               n.iter=n.iter, model.file=model.file)

Giving the error:

Error in checkForRemoteErrors(lapply(cl, recvResult)) : 
  3 nodes produced errors; first error: object 'n.iter' not found

I gather this has something to do with not exporting the variable n.iter to the cluster, but it is not clear what parallel engine jags.parallel is using. Is there any way to trick R to evaluate n.iter before passing it to the function?

1

There are 1 answers

4
Josh O'Brien On BEST ANSWER

do.call() is a great go-to friend in situations like this because (from ?do.call):

If 'quote' is 'FALSE', the default, then the arguments are evaluated (in the calling environment, not in 'envir').

I confirmed that the following works, producing results that match your jagsfit.p through all digits displayed by the result object's print method:

jagsfit.p2 <- do.call(jags.parallel, 
                      list(data=jags.data, inits=jags.inits, jags.params,
                           n.iter=n.iter, model.file=model.file))