#setup environment
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer", 
              "fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer") # 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.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: viridisLite
## 
## 
## Attaching package: 'flextable'
## 
## 
## 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] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [16] "datasets"     "methods"      "base"        
## 
## [[3]]
##  [1] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [16] "datasets"     "methods"      "base"        
## 
## [[4]]
##  [1] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [16] "utils"        "datasets"     "methods"      "base"        
## 
## [[5]]
##  [1] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[6]]
##  [1] "viridis"      "viridisLite"  "fst"          "RColorBrewer" "modelsummary"
##  [6] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [11] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [16] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [21] "methods"      "base"        
## 
## [[7]]
##  [1] "knitr"        "viridis"      "viridisLite"  "fst"          "RColorBrewer"
##  [6] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
## [11] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [16] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [21] "datasets"     "methods"      "base"        
## 
## [[8]]
##  [1] "rmarkdown"    "knitr"        "viridis"      "viridisLite"  "fst"         
##  [6] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
## [11] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [16] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [21] "utils"        "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[10]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[11]]
##  [1] "questionr"    "ggridges"     "rmarkdown"    "knitr"        "viridis"     
##  [6] "viridisLite"  "fst"          "RColorBrewer" "modelsummary" "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[12]]
##  [1] "flextable"    "questionr"    "ggridges"     "rmarkdown"    "knitr"       
##  [6] "viridis"      "viridisLite"  "fst"          "RColorBrewer" "modelsummary"
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[13]]
##  [1] "infer"        "flextable"    "questionr"    "ggridges"     "rmarkdown"   
##  [6] "knitr"        "viridis"      "viridisLite"  "fst"          "RColorBrewer"
## [11] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
## [16] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [21] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"
##Part C - Syntax for Context

#Filter to country and variables of interest
library(fst)
setwd("~/Desktop/SOC202 RESS")
ess <- read_fst("All-ESS-Data.fst")
belgium_data <- ess %>% 
  filter(cntry == "BE") 
write_fst(belgium_data, "~/Desktop/SOC202 RESS/belgium_data.fst")

# clean
 rm(list=ls()); gc()
##           used (Mb) gc trigger   (Mb) limit (Mb)   max used    (Mb)
## Ncells 1261685 67.4    2131461  113.9         NA    2131461   113.9
## Vcells 2151764 16.5 1256338035 9585.1      16384 1351765420 10313.2
 df <- read_fst("~/Desktop/SOC202 RESS/belgium_data.fst")

 # filter the specific year 
df$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
  df$year[df$essround == i] <- replacements[i]
}

belgium_data <- df

#exclude meaningless data
belgium_data_table_subset <- belgium_data %>% 
 mutate(
    happy = ifelse(happy %in% c(77, 88, 99), NA, happy), 
    edulvlb = ifelse(edulvlb %in% c(5555, 7777, 8888, 9999), NA, edulvlb), 
    health = ifelse(health %in% c(77, 88, 99), NA, health),  
  )

datasummary_skim(belgium_data %>% select(happy, edulvlb, health))
Unique (#) Missing (%) Mean SD Min Median Max
happy 14 0 7.8 3.2 0.0 8.0 99.0
edulvlb 20 41 436.4 515.8 0.0 323.0 8888.0
health 8 0 2.1 0.8 1.0 2.0 9.0
belgium_data_v2 <- belgium_data_table_subset %>%
  rename(
    `Happiness` = happy,
    `Highest level of education` = edulvlb,
    `Subjective General Health` = health
  )
summary_table_v2 <- datasummary_skim(belgium_data_v2 %>% select(`Happiness`, `Highest level of education`, `Subjective General Health`), output = "flextable", title ="The basic distribution of three variables in the Belgium data set")
## 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.
summary_table_v2
The basic distribution of three variables in the Belgium data set

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Happiness

12

0

7.7

1.5

0.0

8.0

10.0

Highest level of education

17

42

400.6

200.4

0.0

323.0

800.0

Subjective General Health

8

0

2.1

0.8

1.0

2.0

9.0

##Findings

# Step 1: Calculate the test statistic
belgium_data <- belgium_data %>%
  # Recode "happy" 0 to 10 question, leaving it a numerical variable
  mutate(happy = case_when(
      happy %in% c(77, 88, 99) ~ NA_real_,
      TRUE ~ happy)) %>%
  
   mutate(
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "No BA"
    )) %>%
#add edulvlb data set and recode them into "No BA" and "BA"
  mutate(health = ifelse(health %in% c(7, 8, 9), NA, health))

test_stat <- belgium_data %>%
  specify(explanatory = educ_level,
          response = happy) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "t") 
## Warning: Removed 22 rows containing missing values.
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "BA" - "No BA", or divided in the order "BA" / "No BA" for ratio-based
## statistics. To specify this order yourself, supply `order = c("BA", "No BA")`
## to the calculate() function.
print(test_stat$stat)
##        t 
## 10.01196
# Step 2: Simulate the null distribution
null_distribution <- belgium_data %>%
  specify(explanatory = educ_level,
          response = happy) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "t")
## Warning: Removed 22 rows containing missing values.
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "BA" - "No BA", or divided in the order "BA" / "No BA" for ratio-based
## statistics. To specify this order yourself, supply `order = c("BA", "No BA")`
## to the calculate() function.
# Step 3: Calculate the p-value of sample
p_val <- null_distribution %>%
  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
#visualize
null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided") +
  ggtitle("Figure 1: Simulation-Based Null Distribution")

null_distribution
## Response: happy (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1 -0.131 
##  2         2 -0.0667
##  3         3  0.640 
##  4         4 -0.910 
##  5         5 -0.653 
##  6         6  1.23  
##  7         7  1.57  
##  8         8 -0.881 
##  9         9  1.32  
## 10        10  0.325 
## # ℹ 990 more rows
conf_int <- null_distribution %>%
  get_confidence_interval(level = 0.95, type = "percentile")

null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "greater") +
  shade_confidence_interval(endpoints = conf_int) +
  ggtitle("Figure 1: Simulation-Based Null Distribution")
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

##modeling

#model 1 between educ_level and happy
model1 <- lm(happy ~ educ_level, data = belgium_data, weights = weight)

modelsummary(
  list(model1),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)
educ_levelNo BA −0.2 (0.1)**
Num.Obs. 1767
R2 0.004
R2 Adj. 0.003
AIC 6404.0
BIC 6420.4
Log.Lik. −3198.992
RMSE 1.45
#model2 for health and happy
belgium_data <- belgium_data %>% filter(!is.na(health))
belgium_data <- belgium_data %>%
  mutate(health = ifelse(health %in% c(7, 8, 9), NA, health))
         
# Check the distribution of values in the 'health' variable
table(belgium_data$health)
## 
##    1    2    3    4    5 
## 4033 9262 3338  674  137
model2 <- lm(happy ~ health + educ_level, data = belgium_data, weights = weight)

modelsummary(
  list(model1, model2),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}",
                  "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)   (2)
educ_levelNo BA −0.2 (0.1)** 0.0 (0.1)
health −0.6 (0.0)***
Num.Obs. 1767 1767
R2 0.004 0.100
R2 Adj. 0.003 0.099
AIC 6404.0 6226.0
BIC 6420.4 6247.9
Log.Lik. −3198.992 −3109.017
RMSE 1.45 1.38
#add Model 3 includes an interaction term between health and educ_level without BA
models <- list(
   "Model 1" = lm(happy ~ educ_level, data = belgium_data,  weights = weight),
   "Model 2" = lm(happy ~ health + educ_level, data = belgium_data, weights = weight),
   "Model 3" = lm(happy ~ health + educ_level + health*educ_level, data = belgium_data, weights = weight))
   
modelplot(models, coef_omit = 'Interc') +
  ggtitle("Plot 2: Coefficient Plot")

#finally, create coefficient plot
modelsummary(models, fmt = 1,
  estimate  = c("{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  title = 'Table 2. Regression models predicting happiness')
Table 2. Regression models predicting happiness
Model 1  Model 2  Model 3
(Intercept) 7.9 (0.1)*** 9.0 (0.1)*** 8.8 (0.2)***
educ_levelNo BA −0.2 (0.1)** 0.0 (0.1) 0.2 (0.2)
health −0.6 (0.0)*** −0.5 (0.1)***
health × educ_levelNo BA −0.1 (0.1)
Num.Obs. 1767 1767 1767
R2 0.004 0.100 0.101
R2 Adj. 0.003 0.099 0.099
AIC 6404.0 6226.0 6226.9
BIC 6420.4 6247.9 6254.3
Log.Lik. −3198.992 −3109.017 −3108.473
RMSE 1.45 1.38 1.38
belgium_data$edulvla[belgium_data$edulvla==55] <- NA 
belgium_data$edulvlb[belgium_data$edulvlb==5555] <- NA 
belgium_data$educ_level <- ifelse(belgium_data$essround<5 & belgium_data$edulvla==5, 1,
                      ifelse(belgium_data$essround>=5 & belgium_data$edulvlb>600, 1, 0))

belgium_data$educ_level <- ifelse(belgium_data$educ_level == 1, "BA", "No BA")
# Doing new model & recoding variables of interest

library(effects)
## Loading required package: carData
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
#create interaction plot
model4 <- lm(happy ~ health + educ_level + health * educ_level, data = belgium_data, weights = weight)

# Display the summary of model4
print(summary(model4))
## 
## Call:
## lm(formula = happy ~ health + educ_level + health * educ_level, 
##     data = belgium_data, weights = weight)
## 
## Weighted Residuals:
##     Min      1Q  Median      3Q     Max 
## -65.291  -6.392   1.621   6.765  41.856 
## 
## Coefficients:
##                        Estimate Std. Error t value Pr(>|t|)    
## (Intercept)             8.78965    0.19489  45.102  < 2e-16 ***
## health                 -0.47669    0.09773  -4.877 1.17e-06 ***
## educ_levelNo BA         0.17823    0.22191   0.803    0.422    
## health:educ_levelNo BA -0.11643    0.10797  -1.078    0.281    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 12 on 1755 degrees of freedom
##   (15685 observations deleted due to missingness)
## Multiple R-squared:  0.1015, Adjusted R-squared:  0.09999 
## F-statistic:  66.1 on 3 and 1755 DF,  p-value: < 2.2e-16
# Interaction plot
interaction_plot <- effect("health*educ_level", model4, na.rm = TRUE)

plot(
  interaction_plot,
  main = "Plot3: Interaction effect",
  xlab = "Subejective General Health",
  ylab = "Happiness"
)

interaction_plot
## 
##  health*educ_level effect
##       educ_level
## health       BA    No BA
##      1 8.312956 8.374766
##      2 7.836265 7.781649
##      3 7.359574 7.188532
##      4 6.882882 6.595416
##      5 6.406191 6.002299