Anyway, today I was doing some stuff in R, looked in my workspace, and realized I still had a Gibbs Sampler method, affectionately named GillsGibbs after my professor. So if any of you are looking for a R function that does Gibbs sampling, have at it:
function(mu0,sigma02,shape,scale,data,n)
{
ybar <- mean(data)
out <- matrix(0,n,4)
w2 <- 1/sigma02
sh <- shape + length(data)/2
sigma2 <- 1/(scale*(shape-1))
for (i in 1:n)
{
if (i == 1) {w1 <- length(data)/sigma2}
else {w1 <- length(data)/out[i-1,2]}
postpre<-w1+w2
postvar <- 1/postpre
postsd <- sqrt(postvar)
postmn <- (w1*ybar+w2*mu0)/postpre
out[i,1] <- rnorm(1,postmn,postsd)
ssy <- sum((data-out[i,1])^2)
sc <- 2*scale/(2+scale*ssy)
draw <- rgamma(1,shape=sh,scale=sc)
out[i,2] <- 1/draw
draw1 <- rgamma(1,shape=shape,scale=scale)
draw1 <- 1/draw1
draw2 <- rnorm(1,mu0,sqrt(sigma02))
out[i,3] <- rnorm (1,out[i,1],sqrt(out[i,2]))
out[i,4] <- rnorm(1,draw2,sqrt(draw1))
}
return(out)
}
It's pretty cool.
However, I do have one quick rant: Why does the <code> tag not preserve indentation?
No comments:
Post a Comment