#Title: DWV Assignment 5 Solutions.R
#Author: Jack Reilly
#Purpose: Solve Assignment 5
#Requires: 
#Output: Plots to plot window; nothing to disk

library(tidyverse)
library(haven)

# 1. Use the CES Cumulative File
ces<-read_dta("~/Desktop/working/dwv/datasets/cumulative_2006-2024.dta")

# 2a. Use only 2024 data
ces2024 <- ces |> filter(year== 2024)

# 2b. Recode the 5 category ideology variable to a three category

#Finding data is not always easy in R.  
#Codebooks help!

table(ces2024$ideo5)

#Ugly. A nicer way to look at some tables
library(expss)

cro(ces2024$ideo5)
ces2024$ideo5

attr(ces2024$ideo5, "labels")

# Recoding

ces2024 <- ces2024 |>
  mutate(ideo_r = case_when(
    ideo5 %in% 1:2 ~ 1,
    ideo5 %in% 3 ~ 2,
    ideo5 %in% 4:5 ~ 3,
    ideo5 %in% 6 ~ NA,
  )
  )

#Let's check
cro(ces2024$ideo_r, ces2024$ideo5)

# 3. Recode Presidential Vote

#President vote
table(ces2024$voted_pres_24)
cro(ces2024$voted_pres_24)

ces2024 |>
  count(voted_pres_24, name = "freq") |>
  mutate(pct = freq / sum(freq))

#Recode
ces2024 <- ces2024 |>
  mutate(pres24_trump = case_when(
    voted_pres_24 %in% 1 ~ 0,
    voted_pres_24 %in% 2 ~ 1,
    voted_pres_24 %in% 3:8 ~ NA
  )
  )

#Note here that I labled the dummy variable "trump" to make it easy to remember who is 1 and who is 0
table(ces2024$voted_pres_24, ces2024$pres24_trump)
cro(ces2024$voted_pres_24, ces2024$pres24_trump)

# 5. Recode Home Ownership
# Home own
ces2024$ownhome
table(ces2024$ownhome)
cro(ces2024$ownhome)
attr(ces2024$ownhome, "labels")

ces2024 <- ces2024 |>
  mutate(home_r = case_when(
    ownhome %in% 1 ~ 1,
    ownhome %in% 2 ~ 0,
    ownhome %in% 3 ~ NA
  )
  )

cro(ces2024$ownhome, ces2024$home_r)

# 6. Crosstabs

table(ces2024$pres24_trump, ces2024$home_r)
cro(ces2024$pres24_trump, ces2024$home_r)

# 7. Education

# Education
ces2024$ideo5
table(ces2024$educ)
cro(ces2024$educ)
attr(ces2024$ideo5, "labels")


ces2024 <- ces2024 |>
  mutate(educ_r = case_when(
    educ %in% 1:2 ~ 1,
    educ %in% 3:4 ~ 2,
    educ %in% 5 ~ 3,
    educ %in% 6 ~ 4
  )
  )

table(ces2024$educ, ces2024$educ_r)
cro(ces2024$educ, ces2024$educ_r)

#Now, our cross tabulations
#Simple, unweighted:

cro(ces2024$pres24_trump, ces2024$ideo_r)
cro(ces2024$pres24_trump, ces2024$home_r)
cro(ces2024$pres24_trump, ces2024$educ_r)
