Skip to content

Instantly share code, notes, and snippets.

@TanyaS08
Last active November 22, 2021 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TanyaS08/5ac14d4969bd5d4b772bcdc533999c8f to your computer and use it in GitHub Desktop.
Save TanyaS08/5ac14d4969bd5d4b772bcdc533999c8f to your computer and use it in GitHub Desktop.
Statistical Rethinking Chapter 3 Hard Question 1
# Chapter three
## Hard questions
#' These data indicate the gender (male=1, female=0) of officially reported
#' first and second born children in 100 two-child families.
birth1 =c(1,0,0,0,1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,0,1,0,0,0,1,0,
0,0,0,1,1,1,0,1,0,1,1,1,0,1,0,1,1,0,1,0,0,1,1,0,1,0,0,0,0,0,0,0,
1,1,0,1,0,0,1,0,0,0,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,0,0,1,0,1,1,0,
1,0,1,1,1,0,1,1,1,1)
birth2 =c(0,1,0,1,0,1,1,1,0,0,1,1,1,1,1,0,0,1,1,1,0,0,1,1,1,0,
1,1,1,0,1,1,1,0,1,0,0,1,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,0,0,1,1,
0,0,0,1,1,1,0,0,0,0)
### Question 1
#' Using grid approximation, compute the posterior distribution for the probability
#' of a birth beinga boy. Assume a uniform prior probability. Which parameter value
#' maximises the posterior probability?
# Define parameter values
p = seq(from = 0, to = 1,
length.out = 8128 #'arbitrary'
)
# Define prior (uniform in this case)
prior = rep(0.6, #'arbitrary'
length(p))
# Compute likelihoods
## sum number of boys (i.e. what we observe)
boys = sum(birth1) + sum(birth2)
## get likelihood (binom because binary e.g.)
likelihood = dbinom(boys,
size = 200,
prob = p)
# Get posterior
posterior = likelihood * prior
posterior = posterior / sum(posterior)
# Find the value that maximises posterior probability
p[which.max(posterior)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment