packages <- c("infer", "fst", "modelsummary", "effects", "tidyr", "dplyr", "ggplot2", "questionr", "kableExtra") # 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
## 
## Attaching package: 'kableExtra'
## The following object is masked from 'package:dplyr':
## 
##     group_rows
## [[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"        
## 
## [[8]]
##  [1] "questionr"    "ggplot2"      "dplyr"        "tidyr"        "effects"     
##  [6] "carData"      "modelsummary" "fst"          "infer"        "stats"       
## [11] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [16] "base"        
## 
## [[9]]
##  [1] "kableExtra"   "questionr"    "ggplot2"      "dplyr"        "tidyr"       
##  [6] "effects"      "carData"      "modelsummary" "fst"          "infer"       
## [11] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [16] "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_clean <- uk_data %>%
  select(age, clsprty, vote)

datasummary_skim(uk_data_clean)
Unique (#) Missing (%) Mean SD Min Median Max
age 80 0 51.7 18.1 19.0 51.0 98.0
clsprty 3 1 0.5 0.5 0.0 1.0 1.0
vote 3 3 0.7 0.4 0.0 1.0 1.0
modelage <- table(uk_data_clean$age, uk_data_clean$vote) %>%
  cprop()
  
kbl(modelage, caption = "Conditional Probabilities of Voting and Age", booktabs = T) %>%
  add_header_above(c("Age (Years)", "Did not Vote" = 1, "Voted" = 1, " " = 1)) %>%
  kable_styling(latex_options = c("repeat_header"))
Conditional Probabilities of Voting and Age
Age (Years)
Did not Vote
Voted
0 1 All
19 1.3913384 0.2213614 0.5266118
20 1.9204390 0.4081350 0.8026995
21 2.0576132 0.5118982 0.9151797
22 2.0380169 0.5118982 0.9100670
23 1.9596316 0.6433315 0.9867580
24 2.4887321 0.7678473 1.2168311
25 2.2731726 0.7401771 1.1401401
26 2.5083284 0.8785279 1.3037476
27 2.5083284 0.7263420 1.1912674
28 2.3711542 0.9407858 1.3139731
29 2.3319616 1.1206419 1.4366788
30 2.7630805 1.2589928 1.6514137
31 2.6455026 1.1621472 1.5491590
32 2.3907505 1.3489209 1.6207373
33 2.5475211 1.3281682 1.6463009
34 2.1359984 1.3420033 1.5491590
35 2.4887321 1.5564471 1.7996830
36 2.6455026 1.7017156 1.9479523
37 2.2339800 1.6117875 1.7741193
38 2.4299432 1.4457665 1.7025410
39 2.2927690 1.5356945 1.7332174
40 1.8420537 1.9299945 1.9070505
41 2.1555947 1.7501384 1.8559231
42 1.7440721 1.7086331 1.7178792
43 1.5089163 1.5910349 1.5696099
44 1.7048795 1.8331489 1.7996830
45 1.7244758 1.6878805 1.6974283
46 1.5089163 1.6325401 1.6002863
47 1.7440721 1.6532928 1.6769774
48 1.7636684 1.7708910 1.7690066
49 1.7048795 1.7708910 1.7536684
50 1.7440721 1.6117875 1.6463009
51 1.3717421 1.8054787 1.6923156
52 1.5089163 1.7293857 1.6718646
53 1.4501274 1.5979524 1.5593844
54 1.7048795 1.7708910 1.7536684
55 1.4501274 1.6878805 1.6258500
56 1.2933568 1.9714997 1.7945703
57 1.3913384 1.9299945 1.7894575
58 0.9406232 1.8400664 1.6053990
59 1.1169900 1.9576646 1.7383302
60 1.0777974 1.9922524 1.7536684
61 1.3325495 1.9922524 1.8201340
62 1.1169900 1.9092418 1.7025410
63 1.0386047 1.8193138 1.6156245
64 1.0386047 2.0683453 1.7996830
65 0.8622379 1.8608190 1.6002863
66 0.8818342 2.0199225 1.7229920
67 1.0582011 2.0060874 1.7587811
68 1.0973937 1.7432208 1.5747226
69 0.7838526 1.9922524 1.6769774
70 0.7446600 1.9507471 1.6360755
71 0.8426416 1.6947980 1.4724679
72 0.6662747 1.7363033 1.4571297
73 0.5682932 1.6256226 1.3497623
74 0.6466784 1.5771998 1.3344241
75 0.6466784 1.6048700 1.3548750
76 0.5682932 1.3420033 1.1401401
77 0.7250637 1.4250138 1.2423948
78 0.5682932 1.2313226 1.0583363
79 0.3135411 1.1137244 0.9049542
80 0.4703116 1.1068069 0.9407434
81 0.5291005 1.0929718 0.9458561
82 0.5291005 1.0653016 0.9254052
83 0.4311189 1.0168788 0.8640524
84 0.2939447 0.7263420 0.6135283
85 0.2547521 0.6087438 0.5163863
86 0.2547521 0.5672385 0.4857099
87 0.2939447 0.4911455 0.4396953
88 0.1567705 0.3804649 0.3221024
89 0.1175779 0.3735473 0.3067641
90 0.0783853 0.4288877 0.3374406
91 0.0783853 0.1660210 0.1431566
92 0.0391926 0.1175982 0.0971420
93 0.0195963 0.0760930 0.0613528
94 0.0391926 0.0415053 0.0409019
95 0.0195963 0.0207526 0.0204509
96 0.0000000 0.0069175 0.0051127
97 0.0000000 0.0069175 0.0051127
98 0.0195963 0.0069175 0.0102255
Total 100.0000000 100.0000000 100.0000000
modelcls <- table(uk_data_clean$clsprty, uk_data_clean$vote) %>%
  cprop()
  
kbl(modelcls, caption = "Conditional Probabilities of Voting and Closeness to a Political Party", booktabs = T) %>%
  add_header_above(c("Closeness to Party (1=close, 2=not close)", "Did not Vote" = 1, "Voted" = 1, " " = 1)) %>%
  kable_styling(latex_options = c("repeat_header"))
Conditional Probabilities of Voting and Closeness to a Political Party
Closeness to Party (1=close, 2=not close)
Did not Vote
Voted
0 1 All
0 71.63149 39.57521 47.93865
1 28.36851 60.42479 52.06135
Total 100.00000 100.00000 100.00000
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
interaction_plot <- effect("age*clsprty", model3, 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")

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 = "Mean Vote (No-Yes scale)") + 
  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 = "Mean Vote over Years (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_rect(aes(xmin = 2016, xmax = 2020, ymin = -Inf, ymax = Inf), fill = "grey90", alpha = 0.3) + 
  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 = "Mean Vote Over Years 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