metropolis = function (start=1, n=100, sig.q=1, mu.p=0, sig.p=1) { #starting value theta_0 = start #run for n iterations #set up vector theta[] for the samples theta=rep(NA,n) theta[1]=start #count the number of accepted proposals accept=0 #Main loop for (t in 2:n) { #pick a candidate value theta* from N(theta[t-1], sig.q) theta.star = rnorm(1, theta[t-1], sqrt(sig.q)) #generate a random number between 0 and 1: u = runif(1) # calculate acceptance probability: r = (dnorm(theta.star,mu.p,sig.p)) / (dnorm(theta[t-1],mu.p,sig.p) ) a=min(r,1) #if u