|
Assume the Bayesian model with likelihood Y j Binomial(n; ) and prior Beta(a; b).
(a) Write a function that uses Monte Carlo sampling to estimate the posterior mean and
standard deviation of given we observe Y = y. The function should take inputs y, n,
a, and b. Given these inputs, the function should generate 1; 000; 000 samples of (; Y )
(by rst drawing from a beta distribution and then Y j from a binomial distribution),
extract the samples with Y = y, and return the mean and standard deviation of for
these samples. Include code for this function in your write-up.
(b) Use the code from (1) with n = 10 and a = b = 1 to compute the posterior mean and
standard deviation for for all y = 0; 1; : : : ; n and plot the posterior mean and standard
deviation as a function of y.
MC <- function(y,n,a,b){
theta <- rbeta(1000000,a,b)
Y<- rbinom(1000000,n,theta)
ind <- which(Y==y)
ntheta<-theta(ind)
theta_mn<-mean(ntheta)
theta_sd<-sd(ntheta)
output<-list(mean=theta_mn,
stdev<-theta_sd)
return(output)
}
out1 <- MC(y,n,a,b)
到这一步该怎么做?
|