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 ),
   age_group = case_when(
      age %in% 18:29 ~ "1",
      age %in% 30:39 ~ "2",
      age %in% 40:49 ~ "3",
      age %in% 50:59 ~ "4",
      age %in% 60:69 ~ "5",
      age %in% 70:79 ~ "6",
      age %in% 80:89 ~ "7",
      age %in% 90:100 ~ "8",
      TRUE ~ as.character(age)  # Keeping other values as character if they do not fit the ranges
    ),
    # Converting cohort to a factor with labels
    age_group = factor(age_group,
                 levels = c("1", "2", "3", "4", "5", "6", "7", "8"),
                 labels = c("18-20s", "30s", "40s", "50s", "60s", "70s", "80s", "90s+"))
  ) %>%               # 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 ~ age + clsprty, family = binomial, data = uk_data)
model3 <- glm(vote ~ age + clsprty + age*clsprty, family = binomial, data = uk_data)


modelsummary(
  list(model1, model2, model3),
  fmt = 1,
  estimate  = c(
                "{estimate} ({std.error}){stars}",
                 "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)   (2)   (3)
age 0.0 (0.0)*** 0.0 (0.0)*** 0.0 (0.0)***
clsprty1 1.2 (0.0)*** 1.1 (0.1)***
age × clsprty1 0.0 (0.0)
Num.Obs. 19559 19429 19429
AIC 20890.4 19693.9 19695.8
BIC 20906.2 19717.5 19727.3
Log.Lik. −10443.200 −9843.950 −9843.885
RMSE 0.42 0.41 0.41
exp(coef(model1))
## (Intercept)         age 
##   0.4264918   1.0391027
exp(coef(model2))
## (Intercept)         age    clsprty1 
##   0.3357909   1.0334351   3.1859856
exp(coef(model3))
##  (Intercept)          age     clsprty1 age:clsprty1 
##     0.340399     1.033126     3.068732     1.000785
equatiomatic::extract_eq(model2, use_coefs = TRUE)

\[ \log\left[ \frac { \widehat{P( \operatorname{vote} = \operatorname{1} )} }{ 1 - \widehat{P( \operatorname{vote} = \operatorname{1} )} } \right] = -1.09 + 0.03(\operatorname{age}) + 1.16(\operatorname{clsprty}_{\operatorname{1}}) \]

par(mfrow = c(2,2)) # plot 2 X 2 matrix, by row
plot(model3, pch = 19, col = scales::alpha("grey", .8), cex = .5)

# Running an lm to compare diagnostics

model1 <- lm(vote ~ age, family = binomial, data = uk_data)
## Warning: In lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
##  extra argument 'family' will be disregarded
model2 <- lm(vote ~ age + clsprty, family = binomial, data = uk_data)
## Warning: In lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
##  extra argument 'family' will be disregarded
model3 <- lm(vote ~ age + clsprty + age*clsprty, family = binomial, data = uk_data)
## Warning: In lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
##  extra argument 'family' will be disregarded
modelsummary(
  list(model1, model2, model3),
  fmt = 1,
  estimate  = c(
                "{estimate} ({std.error}){stars}",
                 "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)   (2)   (3)
age 0.0 (0.0)*** 0.0 (0.0)*** 0.0 (0.0)***
clsprty1 0.2 (0.0)*** 0.4 (0.0)***
age × clsprty1 0.0 (0.0)***
Num.Obs. 19559 19429 19429
R2 0.077 0.127 0.131
R2 Adj. 0.077 0.127 0.131
AIC 21760.9 20524.2 20433.5
BIC 21784.6 20555.7 20472.9
Log.Lik. −10877.457 −10258.087 −10211.749
RMSE 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)

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()

Process work: seeing what happens if we group age by decade

model1a <- glm(vote ~ age_group, family = binomial, data = uk_data)
model2b <- glm(vote ~ age_group + clsprty, family = binomial, data = uk_data)
model3c <- glm(vote ~ age_group + clsprty + age_group*clsprty, family = binomial, data = uk_data)



modelsummary(
  list(model1a, model2b, model3c),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)   (2)   (3)
age_group30s 0.6 (0.1)*** 0.6 (0.1)*** 0.5 (0.1)***
age_group40s 1.2 (0.1)*** 1.1 (0.1)*** 1.0 (0.1)***
age_group50s 1.4 (0.1)*** 1.3 (0.1)*** 1.2 (0.1)***
age_group60s 1.8 (0.1)*** 1.6 (0.1)*** 1.5 (0.1)***
age_group70s 2.0 (0.1)*** 1.8 (0.1)*** 1.6 (0.1)***
age_group80s 2.0 (0.1)*** 1.7 (0.1)*** 1.7 (0.1)***
age_group90s+ 2.2 (0.3)*** 2.0 (0.3)*** 2.3 (0.4)***
clsprty1 1.2 (0.0)*** 1.1 (0.1)***
age_group30s × clsprty1 0.1 (0.1)
age_group40s × clsprty1 0.0 (0.1)
age_group50s × clsprty1 0.1 (0.1)
age_group60s × clsprty1 0.2 (0.1)
age_group70s × clsprty1 0.3 (0.2)*
age_group80s × clsprty1 0.0 (0.2)
age_group90s+ × clsprty1 −0.5 (0.6)
Num.Obs. 19559 19429 19429
AIC 20855.5 19651.1 19657.8
BIC 20918.6 19722.0 19783.8
Log.Lik. −10419.770 −9816.568 −9812.915
RMSE 0.42 0.41 0.41
interaction_plot <- effect("age_group*clsprty", model3c, na.rm=TRUE, family = binomial(link = "logit"))

# We plot here the interaction term

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

Process work: Relationship between age and closeness to party

modelz <- glm(vote ~ clsprty, family = binomial, data = uk_data)




modelsummary(
  list(modelz),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}"
               ),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)
clsprty1 1.3 (0.0)***
Num.Obs. 19429
AIC 20731.7
BIC 20747.4
Log.Lik. −10363.831
RMSE 0.42