Created
October 8, 2019 02:14
-
-
Save bayesball/f0a36f84824a4feea55db25b24faf4c7 to your computer and use it in GitHub Desktop.
R script for blog post on five-game playoffs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# plot my prior | |
curve(dnorm(x, .5, .05), .5, .8) | |
title("My Prior") | |
# write a function to compute the log likelihood | |
log_likelihood <- function(p, f){ | |
prob3 <- p ^ 3 + (1 - p) ^ 3 | |
prob4 <- 3 * p ^ 3 * (1 - p) + | |
3 * (1 - p) ^ 3 * p | |
prob5 <- 6 * p ^ 3 * (1 - p) ^ 2 + | |
6 * (1 - p) ^ 3 * p ^ 2 | |
f[1] * log(prob3) + f[2] * log(prob4) + | |
f[3] * log(prob5) | |
} | |
# observed number of 3, 4, and 5 game series | |
f <- c(48, 42, 42) | |
# plot the likelihood | |
p <- seq(.5, .8, by = .001) | |
llike <- log_likelihood(p, f) | |
like <- exp(llike - max(llike)) | |
plot(p, like, type = "l") | |
title("The Likelihood") | |
# function to compute the log posterior | |
log_posterior <-function(p, f){ | |
prob3 <- p ^ 3 + (1 - p) ^ 3 | |
prob4 <- 3 * p ^ 3 * (1 - p) + | |
3 * (1 - p) ^ 3 * p | |
prob5 <- 6 * p ^ 3 * (1 - p) ^ 2 + | |
6 * (1 - p) ^ 3 * p ^ 2 | |
log_like <- f[1] * log(prob3) + f[2] * log(prob4) + | |
f[3] * log(prob5) | |
log_prior <- dnorm(p, 0.5, 0.05, log = TRUE) | |
log_like + log_prior | |
} | |
# plot the posterior | |
p <- seq(.5, .8, by = .001) | |
lpost <- log_posterior(p, f) | |
post <- exp(lpost - max(lpost)) | |
plot(p, post, type = "l") | |
title("The Posterior") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment