listed on r-bloggers.com

Montag, 10. Januar 2011

General-purpose MCMC draw saver for R

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

I also though about using lists. However, since this code actually costs speed I guess it's for quick shots only anyway.


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="") ))
}
}
}
view raw gistfile1.r hosted with ❤ by GitHub

Keine Kommentare:

Kommentar veröffentlichen