p_grid <- seq( from=0 , to=1 , length.out=1000 )


prior <- rep( 1 , 1000 )


likelihood <- dbinom( 6 , size=9 , prob=p_grid )


posterior <- likelihood * prior


posterior <- posterior / sum(posterior)


set.seed(100)


samples <- sample( p_grid , prob=posterior , size=1e4 , replace=TRUE )
plot(p_grid, prior, "l")

plot(p_grid, posterior, "l")

3E1

How much posterior probability lies below p = 0.2?

mean( samples < 0.2)
## [1] 4e-04

3E2.

How much posterior probability lies above p = 0.8?

mean (samples > 0.8)
## [1] 0.1116

3E3

How much posterior probability lies between p = 0.2 and p = 0.8?

mean( samples > 0.2 & samples < 0.8)
## [1] 0.888

3E4

20% of the posterior probability lies below which value of p?

quantile(samples, 0.2)
##       20% 
## 0.5185185

3E5

20% of the posterior probability lies above which value of p?

quantile(samples, 0.8)
##       80% 
## 0.7557558

3E6

HPDI(samples, 0.66)
##     |0.66     0.66| 
## 0.5085085 0.7737738

3E7

Which values of p contain 66% of the posterior probability, assuming equal posterior probability both below and above the interval?

PI(samples, 0.66)
##       17%       83% 
## 0.5025025 0.7697698

3M1

Suppose the globe tossing data had turned out to be 8 water in 15 tosses. Construct the posterior distribution, using grid approximation. Use the same flat prior as before.

p_grid <- seq( from=0 , to=1 , length.out=1000 )


prior <- rep( 1 , 1000 )


likelihood <- dbinom( 8 , size=15 , prob=p_grid )


posterior <- likelihood * prior


posterior <- posterior / sum(posterior)
plot(p_grid, posterior, "l")

3M2

Draw 10,000 samples from the grid approximation from above. Then use the samples to calculate the 90% HPDI for p.

samples <- sample( p_grid , prob=posterior , size=1e4 , replace=TRUE )
HPDI(samples, 0.9)
##      |0.9      0.9| 
## 0.3293293 0.7167167

3M3

Construct a posterior predictive check for this model and data. This means simulate the distribution of samples, averaging over the posterior uncertainty in p. What is the probability of observing 8 water in 15 tosses?

posterior_predictions <- rbinom(samples , size=15 , prob=samples )

mean(posterior_predictions == 8)
## [1] 0.1444

3M4

Using the posterior distribution constructed from the new (8/15) data, now calculate the probability of observing 6 water in 9 tosses.

posterior_predictions <- rbinom(samples , size=9 , prob=samples )

mean(posterior_predictions == 6)
## [1] 0.1751