Setting Up the Environment

setwd("~/SOC252_Assignment")

# Loading Packages
packages <- c ("tidyverse", "fst", "infer", "modelsummary", "forcats", "RColorBrewer",  "viridis", "knitr", "kableExtra", "rmarkdown", "ggridges", "questionr", "effects", "scales")

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: viridisLite
## 
## 
## Attaching package: 'kableExtra'
## 
## 
## The following object is masked from 'package:dplyr':
## 
##     group_rows
## 
## 
## Loading required package: carData
## 
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
## 
## 
## Attaching package: 'scales'
## 
## 
## The following object is masked from 'package:viridis':
## 
##     viridis_pal
## 
## 
## The following object is masked from 'package:purrr':
## 
##     discard
## 
## 
## The following object is masked from 'package:readr':
## 
##     col_factor
## [[1]]
##  [1] "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"     "readr"    
##  [7] "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"     "graphics" 
## [13] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[2]]
##  [1] "fst"       "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"    
##  [7] "readr"     "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"    
## [13] "graphics"  "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[3]]
##  [1] "infer"     "fst"       "lubridate" "forcats"   "stringr"   "dplyr"    
##  [7] "purrr"     "readr"     "tidyr"     "tibble"    "ggplot2"   "tidyverse"
## [13] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"  
## [19] "base"     
## 
## [[4]]
##  [1] "modelsummary" "infer"        "fst"          "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[5]]
##  [1] "modelsummary" "infer"        "fst"          "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[6]]
##  [1] "RColorBrewer" "modelsummary" "infer"        "fst"          "lubridate"   
##  [6] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [11] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"        
## 
## [[7]]
##  [1] "viridis"      "viridisLite"  "RColorBrewer" "modelsummary" "infer"       
##  [6] "fst"          "lubridate"    "forcats"      "stringr"      "dplyr"       
## [11] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [16] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [21] "datasets"     "methods"      "base"        
## 
## [[8]]
##  [1] "knitr"        "viridis"      "viridisLite"  "RColorBrewer" "modelsummary"
##  [6] "infer"        "fst"          "lubridate"    "forcats"      "stringr"     
## [11] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [16] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [21] "utils"        "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "kableExtra"   "knitr"        "viridis"      "viridisLite"  "RColorBrewer"
##  [6] "modelsummary" "infer"        "fst"          "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[10]]
##  [1] "rmarkdown"    "kableExtra"   "knitr"        "viridis"      "viridisLite" 
##  [6] "RColorBrewer" "modelsummary" "infer"        "fst"          "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[11]]
##  [1] "ggridges"     "rmarkdown"    "kableExtra"   "knitr"        "viridis"     
##  [6] "viridisLite"  "RColorBrewer" "modelsummary" "infer"        "fst"         
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[12]]
##  [1] "questionr"    "ggridges"     "rmarkdown"    "kableExtra"   "knitr"       
##  [6] "viridis"      "viridisLite"  "RColorBrewer" "modelsummary" "infer"       
## [11] "fst"          "lubridate"    "forcats"      "stringr"      "dplyr"       
## [16] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [21] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"        
## 
## [[13]]
##  [1] "effects"      "carData"      "questionr"    "ggridges"     "rmarkdown"   
##  [6] "kableExtra"   "knitr"        "viridis"      "viridisLite"  "RColorBrewer"
## [11] "modelsummary" "infer"        "fst"          "lubridate"    "forcats"     
## [16] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [21] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [26] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[14]]
##  [1] "scales"       "effects"      "carData"      "questionr"    "ggridges"    
##  [6] "rmarkdown"    "kableExtra"   "knitr"        "viridis"      "viridisLite" 
## [11] "RColorBrewer" "modelsummary" "infer"        "fst"          "lubridate"   
## [16] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [21] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [26] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [31] "base"
# Loading ESS Data 
ess <- read_fst("All-ESS-Data.fst")

# Creating a year variable
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]}

#Subsetting for Germany, Selecting & Cleaning Variables of Interest

Germany_data <- ess %>%
  filter(cntry == "DE") %>% 

  dplyr::select(
          stflife, eisced, #Focal Variables
          essround, year, #Administrative Variables
          health, hinctnta #Additional Explanatory Variables
         ) %>%
  
    mutate(
    life_satisfaction = ifelse(stflife %in% c(77, 88, 99), NA, stflife),
    eisced = ifelse(eisced %in% c(0, 55, 77, 88, 99), NA, eisced),
      # Creating a new education level variable
      edu_level = case_when(
                            eisced %in% 1:5 ~ 0, #No BA
                            eisced %in% 6:7 ~ 1,#BA
                  ),
    bad_health = ifelse(health %in% c(7, 8, 9), NA, health), #bad health since '1'= Very good health and '5' = Very bad health
    income = ifelse(hinctnta %in% c(77, 88, 99), NA, hinctnta),

  ) %>%
  
drop_na()
    
#Germany_data <- na.omit(Germany_data)

Checking for Unique Values

sapply(lapply(Germany_data, unique), length)
##           stflife            eisced          essround              year 
##                11                 7                 7                 7 
##            health          hinctnta life_satisfaction         edu_level 
##                 5                10                11                 2 
##        bad_health            income 
##                 5                10

Computing datasummary table for main variables of interest

df <- Germany_data %>%
  select(life_satisfaction, edu_level, health, income) 

summary_table <- datasummary_skim(df, output = "flextable") #adding the flextable function to get rid of the tiny histograms
## 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

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

life_satisfaction

11

0

7.3

2.2

0.0

8.0

10.0

edu_level

2

0

0.3

0.4

0.0

0.0

1.0

health

5

0

2.4

0.9

1.0

2.0

5.0

income

10

0

5.7

2.8

1.0

6.0

10.0

Plotting 1st Descriptive Visual - LS Time Trend of Germany vs. ESS baseline

# Computing the average life satisfaction level for Germany by each year
avg_stflife_germany <- Germany_data %>%
  group_by(year) %>%
  summarize(avg_stflife = mean(stflife, na.rm = TRUE)) 

#Computing the average life satisfaction level by year for all ESS countries
avg_stflife_ESS <- ess %>%
  mutate(stflife = ifelse(stflife %in% c(77, 88), NA, stflife)) %>%
  group_by(year) %>%
  summarize(avg_stflife_ess = mean(stflife, na.rm = TRUE))

# Combining Germany data and ess data
combined_data <- left_join(avg_stflife_germany, avg_stflife_ESS, by = "year")

# Reshaping data to better suit the visualization
long_data <- combined_data %>%

pivot_longer(
  cols = starts_with("avg_stflife"),
  names_to = "stflife_type",
  values_to = "AVG_stflife"
  )

# Plotting the Comparison of Germany trend to ESS baseline

p_LS_comparison <- ggplot(long_data) + 
  geom_line(aes(x = year, y = AVG_stflife, color = stflife_type), size = 1) +
  geom_point(aes(x = year, y = AVG_stflife, color = stflife_type), size = 2) +
  scale_x_continuous(breaks = seq(2002, 2020, by=2), limits = c(2002,2020))+
  labs(title = "Life Satisfaction Level in Germany vs. All ESS Countries (2002-2020)", 
       x = "Year", 
       y = "Average Life Satisfaction (0-10 scale)") +
  
  ylim(0,8) +
  
  scale_color_manual(values = c("blue", "darkgrey"),
  name = "Dataset",
  labels = c("Germany", "All ESS Countries"),
  breaks = c("avg_stflife", "avg_stflife_ess")) + 
  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.
p_LS_comparison

# Zooming in on the trends

p_LS_comparison_zoom <- ggplot(long_data) + 
  geom_line(aes(x = year, y = AVG_stflife, color = stflife_type), size = 1) +
  geom_point(aes(x = year, y = AVG_stflife, color = stflife_type), size = 2) +
  scale_x_continuous(breaks = seq(2002, 2020, by=2), limits = c(2002,2020))+
  labs(title = "Life Satisfaction Level in Germany  vs. All ESS Countries (2002-2020)", 
       x = "Year", 
       y = "Average Life Satisfaction (0-10 scale)") +
  
  ylim(6.5,8) +
  
  scale_color_manual(values = c("blue", "darkgrey"),
  name = "Dataset",
  labels = c("Germany", "All ESS Countries"),
  breaks = c("avg_stflife", "avg_stflife_ess")) + 
  theme_minimal()

p_LS_comparison_zoom

Plotting 2nd Descriptive Visual (bivariate) - LS & health

# Relabelling health
Germany_data <- Germany_data %>%
  mutate(
        health = recode (health, 
                         '1' = "Very Good",
                         '2' = "Good",
                         '3' = "Fair",
                         '4' = "Bad",
                         '5' = "Very Bad"
                         ))

LS_health <- Germany_data %>%
  group_by(health) %>%
  summarize(LS_by_health = mean(stflife, na.rm = TRUE)) 

# Reordering Levels 
LS_health$health <- factor(LS_health$health, levels=c('Very Good','Good', 'Fair', 'Bad', 'Very Bad' )) 
LS_health <- LS_health[order(levels(LS_health$health)),] 

# Producing the Visual
library(viridis)

p_health_LS <- ggplot(LS_health, aes(x = health, y = LS_by_health)) +
  geom_segment(aes(xend = health, yend = 0, color = health), size = 1.5)+
  #geom_line(color = "blue", size = 1) +
  geom_point(color = "black", size = 2.5) +
  scale_y_continuous(breaks = 0:10) +
    
    labs(title = "Subjective Health vs. Life satisfaction in Germany",
         x = "Subjective General Health",
         y = "General Satisfaction with Life" 
         )
  theme_minimal()  
## List of 97
##  $ line                      :List of 6
##   ..$ colour       : chr "black"
##   ..$ linewidth    : num 0.5
##   ..$ linetype     : num 1
##   ..$ lineend      : chr "butt"
##   ..$ arrow        : logi FALSE
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_line" "element"
##  $ rect                      :List of 5
##   ..$ fill         : chr "white"
##   ..$ colour       : chr "black"
##   ..$ linewidth    : num 0.5
##   ..$ linetype     : num 1
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_rect" "element"
##  $ text                      :List of 11
##   ..$ family       : chr ""
##   ..$ face         : chr "plain"
##   ..$ colour       : chr "black"
##   ..$ size         : num 11
##   ..$ hjust        : num 0.5
##   ..$ vjust        : num 0.5
##   ..$ angle        : num 0
##   ..$ lineheight   : num 0.9
##   ..$ margin       : 'margin' num [1:4] 0points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : logi FALSE
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ title                     : NULL
##  $ aspect.ratio              : NULL
##  $ axis.title                : NULL
##  $ axis.title.x              :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 2.75points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.x.top          :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 0
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 2.75points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.x.bottom       : NULL
##  $ axis.title.y              :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : num 90
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 2.75points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.y.left         : NULL
##  $ axis.title.y.right        :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 0
##   ..$ angle        : num -90
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 0points 2.75points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text                 :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : chr "grey30"
##   ..$ size         : 'rel' num 0.8
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.x               :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 2.2points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.x.top           :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 0
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 2.2points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.x.bottom        : NULL
##  $ axis.text.y               :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 1
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 2.2points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.y.left          : NULL
##  $ axis.text.y.right         :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 0
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 0points 2.2points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.ticks                : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ axis.ticks.x              : NULL
##  $ axis.ticks.x.top          : NULL
##  $ axis.ticks.x.bottom       : NULL
##  $ axis.ticks.y              : NULL
##  $ axis.ticks.y.left         : NULL
##  $ axis.ticks.y.right        : NULL
##  $ axis.ticks.length         : 'simpleUnit' num 2.75points
##   ..- attr(*, "unit")= int 8
##  $ axis.ticks.length.x       : NULL
##  $ axis.ticks.length.x.top   : NULL
##  $ axis.ticks.length.x.bottom: NULL
##  $ axis.ticks.length.y       : NULL
##  $ axis.ticks.length.y.left  : NULL
##  $ axis.ticks.length.y.right : NULL
##  $ axis.line                 : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ axis.line.x               : NULL
##  $ axis.line.x.top           : NULL
##  $ axis.line.x.bottom        : NULL
##  $ axis.line.y               : NULL
##  $ axis.line.y.left          : NULL
##  $ axis.line.y.right         : NULL
##  $ legend.background         : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ legend.margin             : 'margin' num [1:4] 5.5points 5.5points 5.5points 5.5points
##   ..- attr(*, "unit")= int 8
##  $ legend.spacing            : 'simpleUnit' num 11points
##   ..- attr(*, "unit")= int 8
##  $ legend.spacing.x          : NULL
##  $ legend.spacing.y          : NULL
##  $ legend.key                : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ legend.key.size           : 'simpleUnit' num 1.2lines
##   ..- attr(*, "unit")= int 3
##  $ legend.key.height         : NULL
##  $ legend.key.width          : NULL
##  $ legend.text               :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : 'rel' num 0.8
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ legend.text.align         : NULL
##  $ legend.title              :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 0
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ legend.title.align        : NULL
##  $ legend.position           : chr "right"
##  $ legend.direction          : NULL
##  $ legend.justification      : chr "center"
##  $ legend.box                : NULL
##  $ legend.box.just           : NULL
##  $ legend.box.margin         : 'margin' num [1:4] 0cm 0cm 0cm 0cm
##   ..- attr(*, "unit")= int 1
##  $ legend.box.background     : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ legend.box.spacing        : 'simpleUnit' num 11points
##   ..- attr(*, "unit")= int 8
##  $ panel.background          : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ panel.border              : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ panel.spacing             : 'simpleUnit' num 5.5points
##   ..- attr(*, "unit")= int 8
##  $ panel.spacing.x           : NULL
##  $ panel.spacing.y           : NULL
##  $ panel.grid                :List of 6
##   ..$ colour       : chr "grey92"
##   ..$ linewidth    : NULL
##   ..$ linetype     : NULL
##   ..$ lineend      : NULL
##   ..$ arrow        : logi FALSE
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_line" "element"
##  $ panel.grid.major          : NULL
##  $ panel.grid.minor          :List of 6
##   ..$ colour       : NULL
##   ..$ linewidth    : 'rel' num 0.5
##   ..$ linetype     : NULL
##   ..$ lineend      : NULL
##   ..$ arrow        : logi FALSE
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_line" "element"
##  $ panel.grid.major.x        : NULL
##  $ panel.grid.major.y        : NULL
##  $ panel.grid.minor.x        : NULL
##  $ panel.grid.minor.y        : NULL
##  $ panel.ontop               : logi FALSE
##  $ plot.background           : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ plot.title                :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : 'rel' num 1.2
##   ..$ hjust        : num 0
##   ..$ vjust        : num 1
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 5.5points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ plot.title.position       : chr "panel"
##  $ plot.subtitle             :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 0
##   ..$ vjust        : num 1
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 5.5points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ plot.caption              :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : 'rel' num 0.8
##   ..$ hjust        : num 1
##   ..$ vjust        : num 1
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 5.5points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ plot.caption.position     : chr "panel"
##  $ plot.tag                  :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : 'rel' num 1.2
##   ..$ hjust        : num 0.5
##   ..$ vjust        : num 0.5
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ plot.tag.position         : chr "topleft"
##  $ plot.margin               : 'margin' num [1:4] 5.5points 5.5points 5.5points 5.5points
##   ..- attr(*, "unit")= int 8
##  $ strip.background          : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ strip.background.x        : NULL
##  $ strip.background.y        : NULL
##  $ strip.clip                : chr "inherit"
##  $ strip.placement           : chr "inside"
##  $ strip.text                :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : chr "grey10"
##   ..$ size         : 'rel' num 0.8
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 4.4points 4.4points 4.4points 4.4points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ strip.text.x              : NULL
##  $ strip.text.x.bottom       : NULL
##  $ strip.text.x.top          : NULL
##  $ strip.text.y              :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : num -90
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ strip.text.y.left         :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : num 90
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ strip.text.y.right        : NULL
##  $ strip.switch.pad.grid     : 'simpleUnit' num 2.75points
##   ..- attr(*, "unit")= int 8
##  $ strip.switch.pad.wrap     : 'simpleUnit' num 2.75points
##   ..- attr(*, "unit")= int 8
##  - attr(*, "class")= chr [1:2] "theme" "gg"
##  - attr(*, "complete")= logi TRUE
##  - attr(*, "validate")= logi TRUE
p_health_LS

Cleaning & Adjusting Data to prepare for Analysis

4-Step Hypothesis Testing using the infer package - Education and LS

# Recoding edu_level with labels
Germany_data <- Germany_data %>%
  mutate(
        edu_level = case_when(
                            eisced %in% 1:5 ~ "No BA",     
                            eisced %in% 6:7 ~ "BA"))

#Step 1 - Calculating sample test statistic
test_stat <- Germany_data |>
  specify(explanatory = edu_level, 
          response = life_satisfaction) |>
  hypothesize(null = "independence") |>
  calculate(
    stat = "t",
    order = c("BA", "No BA")
    )

test_stat$stat
##        t 
## 15.94975
# Step 2 - Simulating the null distribution
null_distribution <- Germany_data %>%
  specify(explanatory = edu_level,
          response = life_satisfaction) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "t",
            order = c("BA", "No BA")
            )

# Step 3 - Calculating the p-value of your sample
p_value <- 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_value
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0
# Step 4 - Visualizing sample distribution with respect to null distribution
null_distribution %>%
  visualize() + 
  shade_p_value(obs_stat = test_stat, direction = "two-sided")

null_distribution
## Response: life_satisfaction (numeric)
## Explanatory: edu_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1  1.78  
##  2         2  0.0985
##  3         3 -0.530 
##  4         4  0.545 
##  5         5 -1.22  
##  6         6 -0.589 
##  7         7 -0.564 
##  8         8  0.763 
##  9         9  0.362 
## 10        10 -0.208 
## # ℹ 990 more rows

Modelling & Computing model summary output for all models explored

model1 <- lm(life_satisfaction ~ edu_level, data = Germany_data)
model2 <- lm(life_satisfaction ~ edu_level + income, data = Germany_data)
model3 <- lm(life_satisfaction ~ edu_level + income + bad_health, data = Germany_data)
model4 <- lm(life_satisfaction ~ edu_level + income + bad_health + bad_health*edu_level, data = Germany_data)

modelsummary(
  list(model1, model2, model3, model4),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"), 
  statistic = NULL)
 (1)   (2)   (3)   (4)
(Intercept) 7.6 (0.0)*** 6.2 (0.0)*** 7.8 (0.1)*** 7.5 (0.1)***
edu_levelNo BA −0.5 (0.0)*** −0.1 (0.0)** 0.0 (0.0) 0.3 (0.1)***
income 0.2 (0.0)*** 0.2 (0.0)*** 0.2 (0.0)***
bad_health −0.6 (0.0)*** −0.5 (0.0)***
edu_levelNo BA × bad_health −0.2 (0.0)***
Num.Obs. 21086 21086 21086 21086
R2 0.010 0.073 0.132 0.133
R2 Adj. 0.010 0.073 0.132 0.133
AIC 92135.7 90743.8 89359.8 89341.4
BIC 92159.5 90775.6 89399.5 89389.2
Log.Lik. −46064.834 −45367.887 −44674.883 −44664.713
RMSE 2.15 2.08 2.01 2.01

Checking for assumptions of the Frequentist Approach

# Setting graphical parameters
par(mfrow = c(2,2)) # plot 2 X 2 matrix, by row

# Plotting diagnostics plots
plot(model3, pch = 19, col = scales::alpha("grey", .8), cex = .5)

Calling for the regression equation for the most promising model

summary(model4)
## 
## Call:
## lm(formula = life_satisfaction ~ edu_level + income + bad_health + 
##     bad_health * edu_level, data = Germany_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -8.8536 -0.8986  0.2983  1.2998  5.2533 
## 
## Coefficients:
##                            Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                7.490956   0.087032  86.071  < 2e-16 ***
## edu_levelNo BA             0.344611   0.089518   3.850 0.000119 ***
## income                     0.166920   0.005303  31.478  < 2e-16 ***
## bad_health                -0.483680   0.032442 -14.909  < 2e-16 ***
## edu_levelNo BA:bad_health -0.167479   0.037130  -4.511  6.5e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.013 on 21081 degrees of freedom
## Multiple R-squared:  0.1329, Adjusted R-squared:  0.1327 
## F-statistic: 807.8 on 4 and 21081 DF,  p-value: < 2.2e-16

Bonus: modelling visualization of choice

model4 <- lm(life_satisfaction ~ edu_level + income + bad_health + edu_level*bad_health, data = Germany_data)

interaction_plot <- effect("edu_level*bad_health", model4, na.rm=TRUE)

plot(interaction_plot,
     main="Interaction effect",
     xlab="Education Level (BA vs. No BA)",
     ylab="Bad Health")

interaction_plot
## 
##  edu_level*bad_health effect
##          bad_health
## edu_level        1        2        3        4        5
##     BA    7.964072 7.480391 6.996711 6.513031 6.029350
##     No BA 8.141203 7.490044 6.838884 6.187725 5.536565