Igor — May 31, 2015, 12:52 PM
# This script does Bayesian analysis of the typical
# multi-choice poll (survey), in which people are given
# several choices from which they must choose one
## for more info, see book "Bayesian Computation with R"
## by Jim Albert
library("LearnBayes")
poll <- 1600*0.01*c(29, 36, 19, 7, 9)
n=length(poll)
N.samples <-10000
theta <- rdirichlet(N.samples,poll)
boxplot(theta,col=rainbow(10),horizontal=TRUE)
library(vioplot)
Loading required package: sm
Package 'sm', version 2.2-5.4: type help(sm) for summary information
plot(1,1,ylim=c(0.4,n+0.6),xlim=c(min(theta),max(theta)),type="n",
xlab="posterior values",ylab="answer")
for(i in 1:n)
{
vioplot(theta[,i],
at=i,
add=TRUE,
col="gold", horizontal=TRUE)
}
densities <- list()
ymax <-0
for(i in 1:n)
{
densities[[i]] <- density(theta[,i])
ymax <- max(ymax, max(densities[[i]]$y))
}
## make an empty plot (type ="n") with axis
## limits to contain elements of the figure
plot(NA,NA,type='n',
xlab="theta",ylab="pdf",
xlim=c(min(theta),max(theta)),
ylim=c(0,ymax))
for(i in 1:n)
{
color <- sample(rainbow(8, alpha = .5),1)
polygon(densities[[i]],col=color)
## lines(densities[[i]]$x,densities[[i]]$y,
## type="l",lwd=4,col="red")
}