General-purpose MCMC draw saver for R
[This article was first published on [the] joint posterior distribution, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
If you do MCMC with R, you probably know how nasty “bookkeeping” of draws can be. So I quickly coded up a small function which does everything for you. Every parameter has to begin with “mcmc_” or another to-be-defined string, then just run mcmcsave( ITERATION , # ITERATIONS).Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
I also though about using lists. However, since this code actually costs speed I guess it’s for quick shots only anyway.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mcmcsave = function(rep,R,name_pattern="mcmc_", save_pattern="dMcmc_") { | |
nmp = name_pattern | |
snp = save_pattern | |
mobjects = ls(pattern = nmp, envir=.GlobalEnv) | |
if(rep==1) { | |
for(ii in 1:(length(mobjects))) { | |
namei = substr(mobjects[ii] ,nchar(nmp)+1,nchar(mobjects[ii])) | |
if(is.null(dim(get(mobjects[ii])))) {dims=length(get(mobjects[ii]))} else { | |
dims = dim(get(mobjects[ii]))} | |
assign(paste(snp, namei, sep="") , array(dim=c(R,dims)), envir = .GlobalEnv) | |
}} | |
for(ii in 1:(length(mobjects))) { | |
namei = substr(mobjects[ii] ,nchar(nmp)+1,nchar(mobjects[ii])) | |
dims = dim(get(mobjects[ii])) | |
if(length(dims)==1) { | |
if(dims==1) { | |
tmp = get((mobjects[ii])) | |
eval(parse(text=paste(snp,namei,"[rep]","<-tmp",sep="") )) | |
} else { | |
tmp = get((mobjects[ii])) | |
eval(parse(text=paste(snp,namei,"[rep,]","<-tmp",sep="") )) | |
} | |
} | |
if(length(dims)==2) { | |
tmp = get((mobjects[ii])) | |
eval(parse(text=paste(snp,namei,"[rep,,]","<-tmp",sep="") )) | |
} | |
if(length(dims)==3) { | |
tmp = get((mobjects[ii])) | |
eval(parse(text=paste(snp,namei,"[rep,,,]","<-tmp",sep="") )) | |
} | |
} | |
} |
To leave a comment for the author, please follow the link and comment on their blog: [the] joint posterior distribution.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.