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

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
## [[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] "modelsummary" "fst"          "infer"        "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[6]]
##  [1] "RColorBrewer" "modelsummary" "fst"          "infer"        "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" "fst"         
##  [6] "infer"        "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] "fst"          "infer"        "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" "fst"          "infer"        "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" "fst"          "infer"        "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" "fst"          "infer"       
## [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" "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")

Task 1

switzerland_data <- ess %>%
  filter(cntry == "CH") %>%
  
  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"
    ),
    
    brncntr = recode(brncntr,
                                  `1` = "Yes",
                                  `2` = "No",
                                  `7` = NA_character_,
                                  `8` = NA_character_,
                                  `9` = NA_character_))

switzerland_data <- switzerland_data %>% filter(!is.na(educ_level))
switzerland_data <- switzerland_data %>% filter(!is.na(brncntr))

edubrncntr <- datasummary_crosstab(educ_level ~ brncntr, data = switzerland_data)
edubrncntr
educ_level No Yes All
BA N 1066 2790 3856
% row 27.6 72.4 100.0
No BA N 2801 10266 13067
% row 21.4 78.6 100.0
All N 3867 13056 16923
% row 22.9 77.1 100.0
tab_dat <- switzerland_data

mytab <- table(tab_dat$educ_level, tab_dat$brncntr)

rsums <- rowSums(mytab)

csums <- colSums(mytab)

N <- sum(mytab)
ptab <- tcrossprod(rsums/N, csums/N)
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
print(ptab)
##            [,1]      [,2]
## [1,] 0.05206627 0.1757893
## [2,] 0.17643931 0.5957051
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##           [,1]      [,2]
## [1,]  881.1175  2974.882
## [2,] 2985.8825 10081.118
alpha <- 0.05 # significance level
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841

Interpreting the Critical Value: If the Chi-squared test statistic is greater then 3.841, then we reject the null hypothesis at the 0.05 significance level. This would mean that there is a statistically significant association between education level and if they were born in the country vs Region.

test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 65.1218
p_val <- pchisq(test_stat, df = 1, lower.tail = F)
cat("p-value:", round(p_val, 4), "\n")
## p-value: 0
cat("Chi-squared test result:\n")
## Chi-squared test result:
print(chisq.test(mytab, correct = F))
## 
##  Pearson's Chi-squared test
## 
## data:  mytab
## X-squared = 65.122, df = 1, p-value = 7.041e-16

The p-value is 7.041e-16. The extremely small p-value (essentially 0) means that we reject the null hypothesis that the two variables are independent of each other. This suggests that there is significant association between the two variables education level and if they were born in the country vs Region in mytab. The Pearson’s chi-squared statistic of 65.122 as its greater then the critical value 3.841, also suggests the same results as if the two variables were independent.

Task 2

netherlands_data <- ess %>%
  filter(cntry == "NL") %>%
  
  mutate(
    geo = recode(as.character(domicil), 
                      '1' = "Urban", 
                      '2' = "Urban",
                      '3' = "Rural", 
                      '4' = "Rural", 
                      '5' = "Rural",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_),

    gincdif = recode(as.character(gincdif), 
                      '1' = "Agree", 
                      '2' = "Agree",
                      '3' = NA_character_, 
                      '4' = "Disagree", 
                      '5' = "Disagree",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_)
    )

netherlands_data <- netherlands_data %>% filter(!is.na(geo))
netherlands_data <- netherlands_data %>% filter(!is.na(gincdif))
test_stat <- netherlands_data %>%
  specify(explanatory = geo,
          response = gincdif,
          success = "Agree") %>%
  hypothesize(null = "independence") %>%
  calculate(stat = "z")
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "Rural" - "Urban", or divided in the order "Rural" / "Urban" for
## ratio-based statistics. To specify this order yourself, supply `order =
## c("Rural", "Urban")` to the calculate() function.
print(test_stat$stat)
## [1] -2.422415

The Z-score measures how many standard deviations a particular data point is from the mean in a normal distribution. A z-score of -2.4 suggests that the observed difference between the groups is approximately 2.4 standard deviations below the expected difference, assuming there is no association between recorded as urban or rural and Government should reduce differences in income levels as the p-value has not been calculated yet.

null_dis <- netherlands_data %>%
  specify(explanatory = geo,
          response = gincdif,
          success = "Agree") %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "z")
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "Rural" - "Urban", or divided in the order "Rural" / "Urban" for
## ratio-based statistics. To specify this order yourself, supply `order =
## c("Rural", "Urban")` to the calculate() function.
p_val <- null_dis %>% 
  get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.018

The p-value is less than the threshold 0.05 therefore rejecting the null hypothesis. This suggests that the data point associated with the Z-score is statistically significant, and its an evidence to suggest that it is not consistent with the null hypothesis.

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

null_dis
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 1
##       stat
##      <dbl>
##  1 -1.20  
##  2 -1.12  
##  3  0.335 
##  4  0.453 
##  5  0.335 
##  6  0.0197
##  7  0.374 
##  8 -0.689 
##  9 -1.48  
## 10  1.12  
## # ℹ 990 more rows

The visualization further suggests to reject the null hypothesis or else there should be more shaded red areas (null distributions) as the dark shaded areas (observed).

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


null_dis %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)

The visualization suggests that the observed value is more extreme than what would be expected based on random chance alone. This provides evidence to reject the null hypothesis.

Task 3

research question: How does education relation to happiness in Iceland?

iceland_data <- ess %>%
  filter(cntry == "IS") %>%
  
  mutate(
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    
    # Re-coding education for rounds 5 and later
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    
    # Create educ_level column
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "No BA"
    ),
    
    happy = ifelse(happy %in% c(77, 88, 99), NA, happy)
  )

iceland_data <- iceland_data %>% filter(!is.na(educ_level))
iceland_data <- iceland_data %>% filter(!is.na(happy))
edu_happy_stat <- iceland_data %>%
  specify(explanatory = educ_level,
          response = happy) %>%
  hypothesize(null = "independence") %>%
  calculate(stat = "t")
## 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(edu_happy_stat$stat)
##        t 
## 4.029277

The value represents the number of standard deviations by which the sample mean differs from the null hypothesis and its kind of high, suggesting the mean of happiness level between the two groups (no BA and with BA) is different. The higher the t-statistic value suggests a greater difference between the groups being compared.

null_dist <- iceland_data %>%
  specify(explanatory = educ_level,
          response = happy) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "t")
## 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.
edu_happy_p_val <- null_dist %>% # replace name here if you assigned something other than null_distribution above
  get_pvalue(obs_stat = edu_happy_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.
edu_happy_p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0

The p-value is very small close to 0, suggests we have strong evidence to reject the null hypothesis.

null_dist %>%
  visualize() +
  shade_p_value(obs_stat = edu_happy_stat, direction = "two-sided")

The Visualization indicates clear evidence, to reject the null. Or else there should be as much or more shaded red areas of the null distribution as the observed.

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


null_dist %>%
  visualize() +
  shade_p_value(obs_stat = edu_happy_stat, direction = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)

The visualization suggest the observed result is statistically significant at the chosen confidence level. So the likelihood of obtaining such a result by random chance, assuming the null hypothesis is true, is low. Therefore futher proof to reject the null.