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 variable

Variables: happy - How happy are you (outcome): https://ess.sikt.no/en/datafile/f37d014a-6958-42d4-b03b-17c29e481d3d/256?tab=1&elements=[%22f38e3867-0b7a-46de-9105-639b7a20a981/4%22]

trstplc - Trust in the police (main predictor): https://ess.sikt.no/en/datafile/f37d014a-6958-42d4-b03b-17c29e481d3d/256?tab=1&elements=[%2223725077-a780-4544-aff2-81e85ed7e44d/3%22]

gndr - Gender (secondary predictor): https://ess.sikt.no/en/datafile/f37d014a-6958-42d4-b03b-17c29e481d3d/256?tab=1&elements=[%2279b484a0-5655-46ea-b3c0-dd0b3aaf4dda/5%22]

#Filtering to our country of interest 
finland_data <- ess %>%
  filter(cntry == "FI") 

#Creating a copy
df <- finland_data
df <- df %>%
  mutate(
    #Re-coding outcome happy 0-10
    happy = ifelse(happy %in% c(77, 88, 99), NA, happy
    ),
    # Re-coding main predictor trust in police 0-10
    trstplc = case_when(
      trstplc %in% c(77, 88, 99) ~ NA_real_,
      TRUE ~ trstplc
    ),
    # Re-coding secondary predictor gender
    gndr = case_when(
      gndr == 1 ~ "Male", 
      gndr == 2 ~ "Female",
      gndr == 9 ~ NA_character_,
      TRUE ~ as.character(gndr)))
#Cleaning data
df <- df %>% filter(!is.na(happy))
df <- df %>% filter(!is.na(trstplc))
df <- df %>% filter(!is.na(gndr))

table(finland_data$happy)
## 
##    0    1    2    3    4    5    6    7    8    9   10   77   88 
##   24   26   80  166  231  628  790 2646 6855 6128 1928    4   26
table(finland_data$trstplc)
## 
##    0    1    2    3    4    5    6    7    8    9   10   77   88 
##  100   75  120  187  330  738  942 2325 5474 6554 2643    4   40
table(finland_data$gndr)
## 
##     1     2 
##  9505 10027
#Using data with year range 2016-2022
df$year <- NA
replacements <- c(2016, 2017, 2018, 2019, 2020, 2021, 2022)

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

#graph with data on year zoomed 
happy_avg <- df %>%
  group_by(year) %>%
  summarize(happy_avg = mean(happy, na.rm = TRUE))

plot_zoom_happy <- ggplot(happy_avg, aes(x = year, y = happy_avg)) +
  geom_point(aes(size = happy_avg, color = happy_avg), alpha = 0.7) + 
  geom_line(aes(group = 1), color = "darkgreen", linetype = "dashed") +  
  labs(title = "Average happiness levels by Year (Finland)",
       x = "Survey Year",
       y = "Average Happiness level") +
  theme_minimal() +
  theme(legend.position = "none")

print(plot_zoom_happy)
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 1 row containing missing values (`geom_line()`).

#graph with data on year full scaled
plot_full_scale_happy <- ggplot(happy_avg, aes(x = year, y = happy_avg)) +
  geom_point(aes(size = happy_avg, color = happy_avg), alpha = 0.7) + 
  geom_line(aes(group = 1), color = "darkgreen", linetype = "dashed") +  
  labs(title = "Authoritarian Scale Average by Year (France)",
       x = "Survey Year",
       y = "Average Happiness level") +
  theme_minimal() +
  theme(legend.position = "none") +
  scale_y_continuous(limits = c(0, 10))

print(plot_full_scale_happy)
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Removed 1 row containing missing values (`geom_line()`).

#Creating a data summary table
d <- df %>%
  # Convert factors/characters to numeric
  mutate(
    happy_num = as.numeric(happy),
    trstplc_num = as.numeric(trstplc),
    gender_num = as.numeric(factor(gndr, levels = c("Female", "Male")))
    )
#Renaming and titling 
d <- d %>%
  rename(
    `Happiness` = happy_num,
    `Trust In Police` = trstplc_num,
    `Gender` = gender_num
  )
  
  table1 <- datasummary_skim(d %>% dplyr::select(`Happiness`, `Trust In Police`,`Gender`), title = "Table 1. Descriptive statistics of 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 variables

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Happiness

11

0

8.1

1.4

0.0

8.0

10.0

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

#saving table 1 as a pdf
flextable::save_as_docx(table1, path = "summary_table1.docx",
                       width = 7.0, height = 7.0)

set_flextable_defaults(fonts_ignore=TRUE)

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") 
## Message: The independence null hypothesis does not inform calculation of the
## observed statistic (a slope) and will be ignored.
print(test_stat$stat)
##   trstplc 
## 0.1998413
null_dist <- df %>%
   specify(happy ~ trstplc) %>%
   hypothesize(null = "independence") %>%
   generate(reps = 1000, type = "permute") %>%
   calculate(stat = "slope")

null_dist
## Response: happy (numeric)
## Explanatory: trstplc (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate      stat
##        <int>     <dbl>
##  1         1 -0.000122
##  2         2 -0.00521 
##  3         3  0.00434 
##  4         4 -0.00577 
##  5         5  0.00793 
##  6         6 -0.00581 
##  7         7  0.00943 
##  8         8  0.00364 
##  9         9 -0.00240 
## 10        10  0.00423 
## # ℹ 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
null_dist %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided")

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


null_dist %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)+
  labs(title = "Figure 1. Simulation-Based Null Distribution",
       x = "T statistic",
       y = "Count")

null_dist
## Response: happy (numeric)
## Explanatory: trstplc (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate      stat
##        <int>     <dbl>
##  1         1 -0.000122
##  2         2 -0.00521 
##  3         3  0.00434 
##  4         4 -0.00577 
##  5         5  0.00793 
##  6         6 -0.00581 
##  7         7  0.00943 
##  8         8  0.00364 
##  9         9 -0.00240 
## 10        10  0.00423 
## # ℹ 990 more rows
#More specific version with manually edited instances
test_stat <- 0.1998413

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 0.2 (0.0)*** 0.2 (0.0)*** 0.2 (0.0)***
gndrMale −0.2 (0.0)*** −0.4 (0.1)***
trstplc × gndrMale 0.0 (0.0)+
Num.Obs. 19464 19464 19464
R2 0.057 0.063 0.064
R2 Adj. 0.056 0.063 0.063
AIC 67577.0 67434.9 67433.7
BIC 67600.6 67466.4 67473.1
Log.Lik. −33785.494 −33713.439 −33711.852
RMSE 1.37 1.36 1.36
#Creating another visual 
interaction_plot <- effect("trstplc*gndr", model3, na.rm=TRUE)

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