################################################### ### chunk number 1: ################################################### options(keep.source=TRUE,continue=" ",prompt=" ") ################################################### ### chunk number 2: ################################################### mystery.fun <- function (theta) { 20*dnorm(x=theta,mean=-1,sd=5)+ifelse(theta>-1,6*dgamma(x=theta+1,shape=2,scale=0.5),dgamma(x=-theta,shape=5,scale=0.2))+2*dgamma(x=3-theta,shape=4,scale=0.25) } ################################################### ### chunk number 3: ################################################### require(coda) mcmc.mh <- function (theta, fun, niter, thin = 1) { chain <- matrix( nrow=as.integer(niter), ncol=length(theta), dimnames=list(NULL,names(theta)) ) f <- fun(theta) chain[1,] <- theta k <- 1 # step in the chain nsave <- 1 # number of values saved so far nprop <- 0 # number of proposals made nacpt <- 0 # number of proposals accepted while (nsave < niter) { theta.star <- runif(n=1,min=theta-10,max=theta+10) # propose a new parameter f.star <- fun(theta.star) nprop <- nprop+1 alpha <- f.star/f # Metropolis' rule (since proposal is symmetric) if ((alpha>=1)||(runif(1)