Skip to content

Instantly share code, notes, and snippets.

@elliottmorris
Created July 10, 2025 05:22
Show Gist options
  • Save elliottmorris/c3e3147e23c039c75353a5667a120f4f to your computer and use it in GitHub Desktop.
Save elliottmorris/c3e3147e23c039c75353a5667a120f4f to your computer and use it in GitHub Desktop.
Figuring out who would vote for Musk using ANES data
library(tidyverse)
library(survey)
# mutate weight variable
dat = read_csv('anes_timeseries_2024_csv_20250430.csv') %>%
filter(V241012 == 1) %>%# RVs
mutate(weight = case_when(!is.na(V240103b) ~ V240103b,
!is.na(V240104b) ~ V240104b,
!is.na(V240104b) ~ V240104b,
!is.na(V240103a) ~ V240103a,
!is.na(V240106a) ~ V240106a,
!is.na(V240104a) ~ V240104a,
T ~ NA_real_
),
weight = ifelse(is.na(weight), mean(weight,na.rm=T), weight),
party_id = V241227x,
trump_thermo = V241157,
harris_thermo = V241156,
dems_thermo = V241166,
reps_thermo = V241167,
gov_spending_scale = V241239, # 1 = anti, 7 = pro
dem_7pt_libcon = V241183 # 7 is con
) %>%
select(weight, party_id, trump_thermo, harris_thermo, dems_thermo, reps_thermo,
gov_spending_scale, dem_7pt_libcon)
# sum(is.na(dat$weight))
nrow(dat)
# filter out some obs
dat = dat %>%
mutate_all(function(x){ifelse(x < 0, NA, x)})
nrow(dat)
dat = dat %>%
mutate(typology =
case_when(reps_thermo > 50 &
dems_thermo < 50 &
gov_spending_scale <= 4 ~ 'Hardcore Rep',
reps_thermo < 50 &
dems_thermo > 50 &
gov_spending_scale >= 5 ~ 'Hardcore Dem',
trump_thermo <= 50 & reps_thermo < 50 &
dems_thermo < 50 &
gov_spending_scale < 4 &
dem_7pt_libcon < 3 ~ 'America Party',
reps_thermo > 50 ~ 'Soft Rep',
dems_thermo > 50 ~ 'Soft Dem',
gov_spending_scale >= 5 ~ 'Soft Dem',
gov_spending_scale < 5 ~ 'Soft Rep'
)
)
dat %>%
pull(typology) %>% table(.,useNA = 'always') %>% prop.table()
svy = svydesign(ids = ~1, data = dat, weights = ~weight)
svymean(~typology, svy, na.rm = T)
# strong rep or dem
n = nrow(dat); n
# dem or rep
(dat %>% filter(party_id %in% c(7,6,1,2)) %>% pull(weight) %>% sum) / n
# not dem or rep, but pro trump
(dat %>% filter(!party_id %in% c(7,6,1,2)) %>%
filter(trump_thermo >= 50) %>% pull(weight) %>% sum) / n
# not dem or rep, not pro trump, and wants to keep funding
(dat %>% filter(!party_id %in% c(7,6,1,2)) %>%
filter(trump_thermo <= 50) %>%
filter(gov_spending_scale >= 4) %>% pull(weight) %>% sum) / n
67.5 + 14 + 15.8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment