# List of packages
packages <- c("tidyverse", "infer", "fst", "modelsummary","survey", "MASS", "kableExtra", "flextable", "equatiomatic") # 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)
## ── 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.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ 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: 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] "survey"       "survival"     "Matrix"       "grid"         "modelsummary"
##  [6] "fst"          "infer"        "lubridate"    "forcats"      "stringr"     
## [11] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [16] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [21] "utils"        "datasets"     "methods"      "base"        
## 
## [[6]]
##  [1] "MASS"         "survey"       "survival"     "Matrix"       "grid"        
##  [6] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[7]]
##  [1] "kableExtra"   "MASS"         "survey"       "survival"     "Matrix"      
##  [6] "grid"         "modelsummary" "fst"          "infer"        "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[8]]
##  [1] "flextable"    "kableExtra"   "MASS"         "survey"       "survival"    
##  [6] "Matrix"       "grid"         "modelsummary" "fst"          "infer"       
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[9]]
##  [1] "equatiomatic" "flextable"    "kableExtra"   "MASS"         "survey"      
##  [6] "survival"     "Matrix"       "grid"         "modelsummary" "fst"         
## [11] "infer"        "lubridate"    "forcats"      "stringr"      "dplyr"       
## [16] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [21] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"
ess <- read_fst("All-ESS-Data.fst")

Subsetting to country

switzerland_data <- ess %>%
  filter(cntry == "CH")

# not a bad practice to create a duplicate in case you need to backtrack or use for different purposes
df <- switzerland_data

Cleaining Main Outcome Variables

df <- df %>%
  mutate(wrclmch = wrclmch,
         eisced = eisced) %>%
  mutate(across(c("wrclmch", "eisced"), ~ na_if(.x, 7) %>% na_if(8) %>% na_if(9))) %>%

  mutate(across(c("wrclmch", "eisced"), ~ 7 - .x ))

df$schwartzstflife <- scales::rescale(df$wrclmch + 
                      df$eisced, to=c(0,100), na.rm=T)

# Now you can calculate 'schwartzauth' after the NA recoding
df$stflife <- scales::rescale(df$wrclmch + 
                      df$eisced, to=c(0,100), na.rm=TRUE)


df <- df %>% filter(!is.na(stflife))

ggplot(df, aes(x = stflife)) +
  geom_histogram(bins = 30, fill = "blue", color = "black") +
  theme_minimal() +
  labs(title = "Histogram of Satisfaction Scale",
       x = "Satisfaction Scale",
       y = "Count")

## Average Satisfaction Score by Year for Selected Countries and ESS Baseline

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]
}

ess <- ess %>%
  mutate(wrclmch = wrclmch,
         eisced = eisced) %>%
  mutate(across(c("wrclmch","eisced"),
                ~ na_if(.x, 7) %>% na_if(8) %>% na_if(9))) %>%
  # Apply the reverse coding
  mutate(across(c("wrclmch", "eisced"), ~ 7 - .x ))

# Now you can calculate 'schwartzauth' after the NA recoding
ess$stflife <- scales::rescale(ess$wrclmch + 
                             ess$eisced, to=c(0,100), na.rm=TRUE)
ess_cleaned <- ess %>%
  mutate(
    stflife = stflife,
    year = as.factor(year)  # Ensure year is a factor
  ) %>%
  filter(!is.na(stflife))

# Calculating yearly averages for each country
yearly_stflife_avg <- ess_cleaned %>%
  group_by(cntry, year) %>%
  summarize(avg_stflife = mean(stflife), .groups = 'drop')

# Subset for specific countries and overall ESS baseline
specific_countries_stflife <- yearly_stflife_avg %>%
  filter(cntry %in% c("DE", "IT", "CH"))

ess_baseline_stflife <- ess_cleaned %>%
  group_by(year) %>%
  summarize(avg_stflife = mean(stflife), .groups = 'drop') %>%
  mutate(cntry = "ESS Baseline")

# Combining specific countries with ESS baseline
combined_data_stflife <- rbind(specific_countries_stflife, ess_baseline_stflife)

# Plotting the spaghetti plot for authoritarianism
ggplot(combined_data_stflife, aes(x = year, y = avg_stflife, group = cntry, color = cntry)) +
  geom_line() +
  scale_color_manual(values = c("CH" = "darkgreen", "DE" = "red", "IT" = "yellow")) +
  labs(title = "Average Satisfaction Score by Year for Selected Countries and ESS Baseline",
       x = "Year",
       y = "Satisfaction Score") +
  theme_minimal() +
  theme(legend.position = "right")

## Clean the predictors

df <- df %>%
  mutate(
    wrclmch = case_when(
      wrclmch %in% 1:2 ~ "Not Worried",
      wrclmch %in% 3:3 ~ "Somwhat Worried",
      wrclmch %in% 4:5 ~ "Worried",
      wrclmch %in% c(6, 7, 8, 9) ~ NA_character_      
    ),
    eisced= case_when(
      eisced %in% 0:2 ~ "Low Education",
      eisced %in% 3:5 ~ "Some Education",
      eisced  %in% 6:7 ~ "High Education",
      eisced  %in% c(55, 77, 88, 99) ~ NA_character_
    )
  )

# Extra Cleaning
df <- df %>% filter(!is.na(wrclmch))
df <- df %>% filter(!is.na(eisced))

Hypothesis Testing

test_stat <- df %>%
  specify(explanatory = eisced, # change variable name for explanatory variable
          response = stflife) %>% # change variable name for outcome of interest
  hypothesize(null = "independence") %>%
  calculate(stat = "F") # replace in between quotation marks appropriate test statistic
print(test_stat$stat)
## [1] 1831.41
null_dist <- df %>%
   specify(stflife ~ eisced) %>%
   hypothesize(null = "independence") %>%
   generate(reps = 1000, type = "permute") %>%
   calculate(stat = "F")

null_dist
## Response: stflife (numeric)
## Explanatory: eisced (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 0.223
##  2         2 2.59 
##  3         3 0.180
##  4         4 1.40 
##  5         5 0.400
##  6         6 0.533
##  7         7 1.00 
##  8         8 0.193
##  9         9 1.91 
## 10        10 0.121
## # ℹ 990 more rows
p_val <- null_dist %>% # 
  get_pvalue(obs_stat = test_stat, direction = "greater")
## 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 = "greater") +
  shade_confidence_interval(endpoints = conf_int)
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

# Assuming 'test_stat' is your observed test statistic value
test_stat <- 1208.352

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 = "greater") +
  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 = "F statistic",
       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.
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

test_stat <- df %>%
  specify(explanatory = wrclmch, # change variable name for explanatory variable
          response = stflife) %>% # change variable name for outcome of interest
  hypothesize(null = "independence") %>%
  calculate(stat = "F") # replace in between quotation marks appropriate test statistic
print(test_stat$stat)
## [1] 469.2181
null_dist <- df %>%
   specify(stflife ~ wrclmch) %>%
   hypothesize(null = "independence") %>%
   generate(reps = 1000, type = "permute") %>%
   calculate(stat = "F")

null_dist
## Response: stflife (numeric)
## Explanatory: wrclmch (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1 0.275 
##  2         2 0.490 
##  3         3 2.07  
##  4         4 1.27  
##  5         5 1.58  
##  6         6 8.16  
##  7         7 0.0243
##  8         8 0.831 
##  9         9 0.769 
## 10        10 1.07  
## # ℹ 990 more rows
p_val <- null_dist %>% # 
  get_pvalue(obs_stat = test_stat, direction = "greater")
## 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 = "greater") +
  shade_confidence_interval(endpoints = conf_int)
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

# Assuming 'test_stat' is your observed test statistic value
test_stat <- 593.4386

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 = "greater") +
  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 = "F statistic",
       y = "Count")
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf