Initial set-up

packages <- c("tidyverse", "infer", "fst", "modelsummary", "effects", "survey", "MASS", "kableExtra", "flextable", "equatiomatic")

new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)

lapply(packages, library, character.only = TRUE)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
## Loading required package: carData
## 
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
## 
## Loading required package: grid
## 
## Loading required package: Matrix
## 
## 
## Attaching package: 'Matrix'
## 
## 
## The following objects are masked from 'package:tidyr':
## 
##     expand, pack, unpack
## 
## 
## Loading required package: survival
## 
## 
## Attaching package: 'survey'
## 
## 
## The following object is masked from 'package:graphics':
## 
##     dotchart
## 
## 
## 
## Attaching package: 'MASS'
## 
## 
## The following object is masked from 'package:dplyr':
## 
##     select
## 
## 
## 
## Attaching package: 'kableExtra'
## 
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
## 
## 
## 
## Attaching package: 'flextable'
## 
## 
## The following objects are masked from 'package:kableExtra':
## 
##     as_image, footnote
## 
## 
## The following object is masked from 'package:purrr':
## 
##     compose
## [[1]]
##  [1] "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"     "readr"    
##  [7] "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"     "graphics" 
## [13] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[2]]
##  [1] "infer"     "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"    
##  [7] "readr"     "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"    
## [13] "graphics"  "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[3]]
##  [1] "fst"       "infer"     "lubridate" "forcats"   "stringr"   "dplyr"    
##  [7] "purrr"     "readr"     "tidyr"     "tibble"    "ggplot2"   "tidyverse"
## [13] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"  
## [19] "base"     
## 
## [[4]]
##  [1] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[5]]
##  [1] "effects"      "carData"      "modelsummary" "fst"          "infer"       
##  [6] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [11] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [16] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [21] "methods"      "base"        
## 
## [[6]]
##  [1] "survey"       "survival"     "Matrix"       "grid"         "effects"     
##  [6] "carData"      "modelsummary" "fst"          "infer"        "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[7]]
##  [1] "MASS"         "survey"       "survival"     "Matrix"       "grid"        
##  [6] "effects"      "carData"      "modelsummary" "fst"          "infer"       
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[8]]
##  [1] "kableExtra"   "MASS"         "survey"       "survival"     "Matrix"      
##  [6] "grid"         "effects"      "carData"      "modelsummary" "fst"         
## [11] "infer"        "lubridate"    "forcats"      "stringr"      "dplyr"       
## [16] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [21] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "flextable"    "kableExtra"   "MASS"         "survey"       "survival"    
##  [6] "Matrix"       "grid"         "effects"      "carData"      "modelsummary"
## [11] "fst"          "infer"        "lubridate"    "forcats"      "stringr"     
## [16] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [21] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [26] "utils"        "datasets"     "methods"      "base"        
## 
## [[10]]
##  [1] "equatiomatic" "flextable"    "kableExtra"   "MASS"         "survey"      
##  [6] "survival"     "Matrix"       "grid"         "effects"      "carData"     
## [11] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
## [16] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [21] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [26] "grDevices"    "utils"        "datasets"     "methods"      "base"

Loading dataset

ess <- read_fst("All-ESS-Data.fst")

Creating/cleaning main outcome variable

finland_data <- ess %>%
  filter(cntry == "FI") 

df <- finland_data
df$happy <- ifelse(df$happy > 10, NA, df$happy)
df$happy <- ifelse(df$happy > 10, NA, df$happy)
df$happy <- ifelse(df$happy > 10, NA, df$happy)

# Creating and re-scaling the happy variable
df$happy <- scales::rescale(df$happy + df$happy + df$happy, na.rm = TRUE, to = c(0, 100))

# "flip it" to 'unhappy'?
df$unhappy <- scales::rescale(df$happy, na.rm = TRUE, to=c(100,0))
ggplot(df, aes(x = happy)) +
  geom_histogram(bins = 30, fill = "blue", color = "black") +
  theme_minimal() +
  labs(title = "Histogram of Populist Scale",
       x = "Populist Scale",
       y = "Count")
## Warning: Removed 30 rows containing non-finite values (`stat_bin()`).

df$year <- NA
replacements <- c(2016, 2017, 2018, 2019, 2020, 2021, 2022)

for (i in 1:7) {
  df$year[df$essround == i] <- replacements[i]
}

Cleaning predictors and generating tables

df <- df %>%
  mutate(
    # Re-coding trust in police 0-10
    trstplc = case_when(
      trstplc %in% c(77, 88, 99) ~ NA_real_,
      TRUE ~ trstplc
    ),
    # Re-coding gender
    gndr = case_when(
      gndr == 1 ~ "Male",
      gndr == 2 ~ "Female",
      gndr == 9 ~ NA_character_,
      TRUE ~ as.character(gndr)
  )
)

df <- df %>% filter(!is.na(trstplc))
df <- df %>% filter(!is.na(gndr))
d <- df %>%
  # Convert factors/characters to numeric
  mutate(
    trstplc_num = as.numeric(trstplc),
    gender_num = as.numeric(factor(gndr, levels = c("Female", "Male")))
    )
d <- d %>%
  rename(
    `Trust In Police` = trstplc_num,
    `Gender` = gender_num,
    `Happy` = happy
  )
  
  table1 <- datasummary_skim(d %>% dplyr::select(`Trust In Police`,`Gender`, `Happy`), title = "Table 1. Descriptive statistics of main variables", output = "flextable")
## Warning: The histogram argument is only supported for (a) output types "default",
##   "html", "kableExtra", or "gt"; (b) writing to file paths with extensions
##   ".html", ".jpg", or ".png"; and (c) Rmarkdown, knitr or Quarto documents
##   compiled to PDF (via kableExtra)  or HTML (via kableExtra or gt). Use
##   `histogram=FALSE` to silence this warning.
table1
Table 1. Descriptive statistics of main variables

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Trust In Police

11

0

8.1

1.7

0.0

8.0

10.0

Gender

2

0

1.5

0.5

1.0

1.0

2.0

Happy

12

0

80.7

14.1

0.0

80.0

100.0

#just showing the categorical variables
table2 <- datasummary_skim(d  %>% dplyr::select(gndr), type = "categorical", title = "Table 1.5. Categorical Predictors Summary", output = "flextable")

table2
Table 1.5. Categorical Predictors Summary

gndr

N

%

Female

9990

51.3

Male

9498

48.7

Hypothesis testing

test_stat <- df %>%
  specify(explanatory = trstplc, # change variable name for explanatory variable
          response = happy) %>% # change variable name for outcome of interest
  hypothesize(null = "independence") %>%
  calculate(stat = "slope") 
## Warning: Removed 24 rows containing missing values.
## Message: The independence null hypothesis does not inform calculation of the
## observed statistic (a slope) and will be ignored.
print(test_stat$stat)
##  trstplc 
## 1.998413
null_dist <- df %>%
   specify(happy ~ trstplc) %>%
   hypothesize(null = "independence") %>%
   generate(reps = 1000, type = "permute") %>%
   calculate(stat = "slope")
## Warning: Removed 24 rows containing missing values.
null_dist
## Response: happy (numeric)
## Explanatory: trstplc (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1  0.0784
##  2         2 -0.0673
##  3         3 -0.0484
##  4         4 -0.0260
##  5         5  0.0530
##  6         6  0.0536
##  7         7  0.0604
##  8         8  0.0369
##  9         9 -0.0427
## 10        10 -0.0847
## # ℹ 990 more rows
p_val <- null_dist %>% # 
  get_pvalue(obs_stat = test_stat, direction = "two-sided")
## Warning: Please be cautious in reporting a p-value of 0. This result is an
## approximation based on the number of `reps` chosen in the `generate()` step.
## See `?get_p_value()` for more information.
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0
conf_int <- null_dist%>%
  get_confidence_interval(level = 0.95, type = "percentile")


null_dist %>%
  visualize(data, bins = 10, method = "simulation", dens_color = "black") +
  shade_p_value(obs_stat = test_stat, direction = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)

test_stat <- 1.998413

conf_int <- null_dist %>%
  get_confidence_interval(level = 0.95, type = "percentile")

# Visualize the null distribution with manual x-axis limits
null_dist %>%
  visualize(bins = 15, method = "simulation", dens_color = "black") +
  geom_vline(aes(xintercept = test_stat), color = "red", linetype = "dashed", size = 1) +
  shade_p_value(obs_stat = test_stat, direction = "two-sided") +
  shade_confidence_interval(endpoints = conf_int) +
  coord_cartesian(xlim = c(0, max(null_dist$stat) * 1.1)) + # Set manual x-axis limits
  labs(title = "Simulation-Based Null Distribution",
       x = "Linear Regression",
       y = "Count")
## 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.

Modeling

df$weight <- df$dweight * df$pweight
model1 <- lm(happy ~ trstplc, data = df, weights = weight)
model2 <- lm(happy ~ trstplc + gndr, data = df, weights = weight)
model3 <- lm(happy ~ trstplc + trstplc*gndr, data = df, weights = weight)
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)
trstplc 2.0 (0.1)*** 2.0 (0.1)*** 1.9 (0.1)***
gndrMale −2.4 (0.2)*** −4.0 (1.0)***
trstplc × gndrMale 0.2 (0.1)+
Num.Obs. 19464 19464 19464
R2 0.057 0.063 0.064
R2 Adj. 0.056 0.063 0.063
AIC 157212.0 157069.9 157068.7
BIC 157235.6 157101.4 157108.1
Log.Lik. −78603.010 −78530.956 −78529.368
RMSE 13.69 13.63 13.63
interaction_plot <- effect("trstplc*gndr", model3, na.rm=TRUE)

plot(interaction_plot,
     main="Interaction effect",
     xlab="Trust in Police levels",
     ylab="Happiness levels")