Setup Environment

packages <- c("tidyverse", "infer", "fst", "modelsummary", "effects", "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.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"
tinytex::install_tinytex(force = TRUE)
## tlmgr install multirow

Set working directory

setwd("~/Desktop/SOC202_R_Coding")

Load Dataset

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

Part C - Syntax for Context

Filter to country and variables of interest

1: Education Levels + Total Net Income

uk_data <- ess %>%
  filter(cntry == "GB") %>%
  mutate(
    happy = ifelse(happy %in% c(77,88,99), NA, happy),
    
    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"),
    
    hinctnta = ifelse(hinctnta %in% 0:10, hinctnta, NA)
  )

df <- uk_data

Ensure proper cleaning of all variables

uk_data <- uk_data %>% filter(!is.na(happy))
uk_data <- uk_data %>% filter(!is.na(educ_level))
uk_data <- uk_data %>% filter(!is.na(hinctnta))

table(uk_data$happy)
## 
##    0    1    2    3    4    5    6    7    8    9   10 
##   66   54  152  283  373  839  850 2174 3627 2247 1425
table(uk_data$educ_level)
## 
##    BA No BA 
##  3631  8459
table(uk_data$hinctnta)
## 
##    1    2    3    4    5    6    7    8    9   10 
## 1700 1516 1305 1058 1049 1052 1138 1096  970 1206

Convert Factors to Numerics

uk_data <- uk_data %>%
  mutate(
    happy = as.numeric(factor(happy)),
    educ_level = as.numeric(factor(educ_level, levels = c("BA", "No BA"))),
    hinctnta_num = as.numeric(factor(hinctnta, levels = c("High","Middle", "Low")))
  )
table1 <- datasummary_skim(uk_data  %>% dplyr::select(happy, educ_level, hinctnta), 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

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

happy

11

0

8.5

1.9

1.0

9.0

11.0

educ_level

2

0

1.7

0.5

1.0

2.0

2.0

hinctnta

10

0

5.1

3.0

1.0

5.0

10.0

Relabel the Data Summary Table

uk_data <- uk_data %>%
  rename(
    `Happiness` = happy,
    `Level of Education` = educ_level,
    `Total Net Income` = hinctnta
  )
  
  table1_v2 <- datasummary_skim(uk_data %>% dplyr::select(`Happiness`,`Level of Education`, `Total Net Income`), title = "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_v2
Descriptive Statistics of Variables

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Happiness

11

0

8.5

1.9

1.0

9.0

11.0

Level of Education

2

0

1.7

0.5

1.0

2.0

2.0

Total Net Income

10

0

5.1

3.0

1.0

5.0

10.0

Save the Table

flextable::save_as_docx(table1_v2, path = "summary_table1_v2.docx", # change name to whatever you would like
                       width = 7.0, height = 7.0) # play around with dimensions

set_flextable_defaults(fonts_ignore=TRUE)
print(table1_v2, preview = "pdf")
## a flextable object.
## col_keys: ` `, `Unique (#)`, `Missing (%)`, `Mean`, `SD`, `Min`, `Median`, `Max` 
## header has 1 row(s) 
## body has 3 row(s) 
## original dataset sample: 
##                      Unique (#) Missing (%) Mean  SD Min Median  Max
## 1          Happiness         11           0  8.5 1.9 1.0    9.0 11.0
## 2 Level of Education          2           0  1.7 0.5 1.0    2.0  2.0
## 3   Total Net Income         10           0  5.1 3.0 1.0    5.0 10.0

Part D - Infer Package for Findings

uk_data <- ess %>%
  filter(cntry == "GB") %>%
  mutate(
   happy = ifelse(happy %in% c(77,88,99),NA,happy),
    
   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"),
       hinctnta = ifelse(hinctnta %in% 0:10, hinctnta, NA)
)

P1: Calculate Test Statistic of Sample

test_stat <- uk_data %>%
  specify(explanatory = educ_level, 
          response = happy) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "t")
## Warning: Removed 33 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 
## 7.252408

A test stastic value of 7.25 is decently high indicating that there is a difference between happiness for those with an educational attainment of a BA than those without. It evidences that mean happiness levels are different for BA and NO BA individuals.

P2: Simulate the ND

null_distribution <- uk_data %>%
  specify(explanatory = educ_level,
          response = happy) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%  
  calculate(stat = "t")
## Warning: Removed 33 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.
null_distribution
## Response: happy (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1  0.338
##  2         2 -0.791
##  3         3  0.618
##  4         4 -0.128
##  5         5  0.228
##  6         6 -2.16 
##  7         7 -0.850
##  8         8 -2.00 
##  9         9  0.708
## 10        10  1.63 
## # ℹ 990 more rows

Step 3 - Calculate P-value

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

The p-value we attained is 0 suggesting that there is strong evidence for us to be able to reject the null hypothesis.

Step 4 - Create Visualization:

null_distribution %>%
  visualize()+
  shade_p_value(obs_stat = test_stat, direction = "two-sided")

With a 95% confidence interval, we can reject the null hypothesis because the test statistic falls oustide of the simulated T Null Distribution.I used the t-statistic to explain because I have two explanatory vairables resulting in one numeric variable.

null_distribution
## Response: happy (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1  0.338
##  2         2 -0.791
##  3         3  0.618
##  4         4 -0.128
##  5         5  0.228
##  6         6 -2.16 
##  7         7 -0.850
##  8         8 -2.00 
##  9         9  0.708
## 10        10  1.63 
## # ℹ 990 more rows

Part D - Finding 2: Regression Modelling Output

Use modelsummary here and specify the 3 models - single, multivariate, and interaction

uk_data$weight <- uk_data$dweight * uk_data$pweight
model1 <- lm(happy ~ educ_level, data = uk_data, weights = weight)
model2 <- lm(happy ~ educ_level + hinctnta, data = uk_data, weights = weight)
model3 <- lm(happy ~ educ_level + hinctnta*educ_level, data = uk_data, 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)
educ_levelNo BA −0.2 (0.0)*** 0.0 (0.0) 0.0 (0.1)
hinctnta 0.1 (0.0)*** 0.1 (0.0)***
educ_levelNo BA × hinctnta 0.0 (0.0)
Num.Obs. 20946 12090 12090
R2 0.002 0.029 0.029
R2 Adj. 0.002 0.029 0.029
AIC 88089.7 50261.8 50263.1
BIC 88113.5 50291.4 50300.1
Log.Lik. −44041.842 −25126.909 −25126.547
RMSE 1.91 1.86 1.86

Part D - Finding 3: Interactional Plot (Visual of Choice)

uk_data$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
  uk_data$year[df$essround == i] <- replacements[i]
}
happy <- uk_data %>%
  group_by(educ_level) %>%
  summarize(happy = mean(happy, na.rm = TRUE))

plot_zoom_happy <- ggplot(happy, aes(x = educ_level, y = happy)) +
  geom_point(aes(size = happy, color = happy), alpha = 0.7) + 
  geom_line(aes(group = 1), color = "blue", linetype = "dashed") +  
  labs(title = "Happiness Levels Based on Educational Attaiment (United Kingdom))",
       x = "Educational Attainment",
       y = "Happiness Levels") +
  theme_minimal() +
  theme(legend.position = "none")

print(plot_zoom_happy)