Created
November 27, 2023 22:50
-
-
Save elliottmorris/7bd62da8b71c10801b492f9c0b1afa97 to your computer and use it in GitHub Desktop.
for twitter. showing how to combine a prior (past election results) and data (polls) for certain poll subgroups
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
library(tidyverse) | |
bayes_update_normal = function( | |
data_mu, | |
data_se, | |
prior_mu = 0, | |
prior_se = 3){ | |
if(all(data_mu == 0)){ | |
return(c(0,0)) | |
} | |
# calc precision | |
data_pre = 1/(data_se^2) | |
prior_pre = 1/(prior_se^2) | |
# new mu | |
post_mu = | |
( (prior_pre / (prior_pre + data_pre)) * prior_mu ) + | |
( (data_pre / (prior_pre + data_pre)) * data_mu ) | |
# new variance (then sd) | |
post_var = ( ((data_se^2)/1) * prior_se^2 ) / | |
(prior_se^2 + ((data_se^2)/1)) | |
post_se = sqrt(post_var) | |
list(post_mu,post_se) | |
} | |
prior = rnorm(200000, 24, 5) | |
data = rnorm(200000, 4, 10) | |
post = bayes_update_normal(mean(data), sd(data), mean(prior), sd(prior)) | |
post = rnorm(200000, post[[1]], post[[2]]) | |
chart = tibble(prior = prior, | |
data = data, | |
post = post) | |
ggplot(chart) + | |
geom_vline(xintercept = 0, col = 'gray60') + | |
geom_density(aes(x=prior, col = '1. Past vote (24 +/- 5)')) + | |
geom_density(aes(x=data, col = '2. Polls (+4 +/- 10)')) + | |
geom_density(aes(x=post, col = '3. Posterior')) + | |
theme_minimal() + | |
labs(x = "Democratic presidential vote margin", | |
y = '', | |
subtitle = 'Scenario: Very tight prior, low trust in polls', | |
col = '', | |
title = 'Updating a prior for young voters with polls') + | |
theme(axis.title.y = element_blank(), | |
axis.ticks.y = element_blank(), | |
axis.text.y = element_blank(), | |
panel.grid.minor = element_blank(), | |
legend.position = 'top') + | |
coord_cartesian(xlim=c(-50,50)) | |
mean(post) | |
sd(post) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment