Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...