#generate data
set.seed(123)
n=150; y=rnorm(n,4,1)
Copyright By PowCoder代写 加微信 powcoder
#known variance and prior
sigma2=1; mu0=0; sigma20=100
S=10000; mu=numeric(S); mu[1]=rnorm(1,mu0,sqrt(sigma20))
for(i in 2:S){
mustar=rnorm(1,mean=mu[i-1],sd=sqrt(s2))
p1=sum(dnorm(y,mean=mustar,sd=sqrt(sigma2),log=TRUE))+dnorm(mustar,mean=mu0,sd=sqrt(sigma20),log=TRUE)
p2=sum(dnorm(y,mean=mu[i-1],sd=sqrt(sigma2),log=TRUE))+dnorm(mu[i-1],mean=mu0,sd=sqrt(sigma20),log=TRUE)
u=runif(1)
if(log(u)