packages <- c("infer", "fst", "modelsummary", "effects", "tidyr", "dplyr", "ggplot2") # add any you need here

# Install packages if they aren't installed already
new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)

# Load the packages
lapply(packages, library, character.only = TRUE)
## Loading required package: carData
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
## [[1]]
## [1] "infer"     "stats"     "graphics"  "grDevices" "utils"     "datasets" 
## [7] "methods"   "base"     
## 
## [[2]]
## [1] "fst"       "infer"     "stats"     "graphics"  "grDevices" "utils"    
## [7] "datasets"  "methods"   "base"     
## 
## [[3]]
##  [1] "modelsummary" "fst"          "infer"        "stats"        "graphics"    
##  [6] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[4]]
##  [1] "effects"      "carData"      "modelsummary" "fst"          "infer"       
##  [6] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [11] "methods"      "base"        
## 
## [[5]]
##  [1] "tidyr"        "effects"      "carData"      "modelsummary" "fst"         
##  [6] "infer"        "stats"        "graphics"     "grDevices"    "utils"       
## [11] "datasets"     "methods"      "base"        
## 
## [[6]]
##  [1] "dplyr"        "tidyr"        "effects"      "carData"      "modelsummary"
##  [6] "fst"          "infer"        "stats"        "graphics"     "grDevices"   
## [11] "utils"        "datasets"     "methods"      "base"        
## 
## [[7]]
##  [1] "ggplot2"      "dplyr"        "tidyr"        "effects"      "carData"     
##  [6] "modelsummary" "fst"          "infer"        "stats"        "graphics"    
## [11] "grDevices"    "utils"        "datasets"     "methods"      "base"
ess <- read_fst("All-ESS-Data.fst")
table(ess$essround)
## 
##     1     2     3     4     5     6     7     8     9    10 
## 42359 47537 43000 56752 52458 54673 40185 44387 49519 59685
ess$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
  ess$year[ess$essround == i] <- replacements[i]
}
table(ess$year)
## 
##  2002  2004  2006  2008  2010  2012  2014  2016  2018  2020 
## 42359 47537 43000 56752 52458 54673 40185 44387 49519 59685
uk_data <- ess %>%
  filter(cntry == "GB") %>%
   mutate(
    age = ifelse(agea == 999, NA, agea),
    hinctnta = ifelse(hinctnta %in% c(77, 88, 99), NA, hinctnta),
    vote = ifelse(vote == 2, 0, ifelse(vote %in% c(3, 7, 8, 9), NA, vote)),
    clsprty = case_when(
    clsprty == 1 ~ 1,              # Keep 1 as numeric
    clsprty == 2 ~ 0,              # Recode 2 as numeric 0
    clsprty %in% c(7, 8, 9) ~ NA_real_,  # Set 7, 8, 9 as NA keeping the type numeric
    TRUE ~ clsprty ))  %>%               # Keep all other values as they are
filter(age > 18 & age < 100)
uk_data$clsprty <- as.factor(uk_data$clsprty)
model1 <- glm(vote ~ age, family = binomial, data = uk_data)
model2 <- glm(vote ~ clsprty, family = binomial, data = uk_data)
model3 <- glm(vote ~ age + clsprty, family = binomial, data = uk_data)
model4 <- glm(vote ~ age + clsprty + age*clsprty, family = binomial, data = uk_data)



modelsummary(
  list(model1, model2, model3, model4),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)   (2)   (3)   (4)
age 0.0 (0.0)*** 0.0 (0.0)*** 0.0 (0.0)***
clsprty1 1.3 (0.0)*** 1.2 (0.0)*** 1.1 (0.1)***
age × clsprty1 0.0 (0.0)
Num.Obs. 19559 19429 19429 19429
AIC 20890.4 20731.7 19693.9 19695.8
BIC 20906.2 20747.4 19717.5 19727.3
Log.Lik. −10443.200 −10363.831 −9843.950 −9843.885
RMSE 0.42 0.42 0.41 0.41
par(mfrow = c(2,2)) # plot 2 X 2 matrix, by row
plot(model3, pch = 19, col = scales::alpha("grey", .8), cex = .5)

interaction_plot <- effect("age*clsprty", model4, na.rm=TRUE)

# We plot here the interaction term

plot(interaction_plot,
     main="Interaction effect Age Group x close to party",
     xlab="Age",
     ylab="Vote")

vote_by_age <- uk_data %>%
  group_by(age) %>%
 summarize(mean_vote = mean(vote, na.rm = TRUE))
vote_by_age
## # A tibble: 80 × 2
##      age mean_vote
##    <dbl>     <dbl>
##  1    19     0.311
##  2    20     0.376
##  3    21     0.413
##  4    22     0.416
##  5    23     0.482
##  6    24     0.466
##  7    25     0.480
##  8    26     0.498
##  9    27     0.451
## 10    28     0.529
## # ℹ 70 more rows
ggplot (data = vote_by_age,
        mapping = aes(x = age,
y = mean_vote,
color = "red")) +
  geom_smooth() +
  labs(title = "Voting by Age", x = "Age", y = "Likelihood to Vote") + 
  ylim (0,1) +
  geom_point()
## `geom_smooth()` using method = 'loess' and formula = 'y ~ x'

vote_by_year <- uk_data %>%
  group_by(year) %>%
 summarize(mean_vote = mean(vote, na.rm = TRUE))
vote_by_year
## # A tibble: 10 × 2
##     year mean_vote
##    <dbl>     <dbl>
##  1  2002     0.732
##  2  2004     0.697
##  3  2006     0.731
##  4  2008     0.716
##  5  2010     0.725
##  6  2012     0.723
##  7  2014     0.716
##  8  2016     0.774
##  9  2018     0.803
## 10  2020     0.810
ggplot(vote_by_year, aes(x = year, y = mean_vote)) +
  geom_line(color = "blue", size = 1) +  # Line to show the trend
  geom_point(color = "red", size = 3) +  # Points to highlight each year's value
  labs(title = "Average of Respondents who said they Voted (2002-2020)", 
       x = "Year", 
       y = "Mean Vote (No-Yes scale)") +
  ylim(0, 1) + 
  theme_minimal()
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

ess$vote[ess$vote %in% c(3, 7, 8, 9)] <- NA
ess_data_clean <- ess %>%
  select(vote, essround, year)  %>%
  mutate(
     vote = ifelse(vote == 2, 0, ifelse(vote %in% c(3, 7, 8, 9), NA, vote))
  )

avg_vote_uk <- uk_data %>%
  group_by(year) %>%
  summarize(mean_vote_uk = mean(vote, na.rm = TRUE))
avg_vote_all_countries <- ess_data_clean %>%
  group_by(year) %>%
  summarize(mean_vote_all = mean(vote, na.rm = TRUE))
avg_vote_all_countries
## # A tibble: 10 × 2
##     year mean_vote_all
##    <dbl>         <dbl>
##  1  2002         0.802
##  2  2004         0.770
##  3  2006         0.779
##  4  2008         0.776
##  5  2010         0.763
##  6  2012         0.760
##  7  2014         0.766
##  8  2016         0.766
##  9  2018         0.785
## 10  2020         0.817
combined_data <- left_join(avg_vote_uk, avg_vote_all_countries, by = "year")
long_data <- combined_data %>%
  pivot_longer(
    cols = starts_with("mean_vote"), 
    names_to = "Vote_Type",  
    values_to = "Mean_Vote"  
  )

ggplot(long_data) +
  geom_line(aes(x = year, y = Mean_Vote, color = Vote_Type), size = 1) +
  geom_point(aes(x = year, y = Mean_Vote, color = Vote_Type), size = 3) +
  labs(title = "Average of Respondents who said they Voted UK vs Europe (2002-2020)", 
       x = "Year", 
       y = "Mean Vote (No-Yes scale)") +
  ylim(0, 1) +
  scale_color_manual(values = c("blue", "red"), 
                     name = "Dataset", 
                     labels = c("UK", "All ESS"), 
                     breaks = c("mean_vote_uk", "mean_vote_all")) + 
  theme_minimal()