packages <- c("tidyverse", "infer", "fst")

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
## [[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"
library(fst)
setwd("~/SOC202/R Scripts (hw + tutorial)/Maa_Cassiopeia_Project_202")
ess <- read_fst("All-ESS-Data.fst")

Task 1

table(ess$essround)
## 
##     1     2     3     4     5     6     7     8     9    10 
## 42359 47537 43000 56752 52458 54673 40185 44387 49519 59685
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]
}

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

#Recoding
switzerland_data <- switzerland_data %>%
  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"
    )
  )

table(switzerland_data$educ_level)
## 
##    BA No BA 
##  3856 13069
switzerland_data <- switzerland_data %>%
  mutate(born_in_country = recode(brncntr,
                                  `1` = "Yes",
                                  `2` = "No",
                                  `7` = NA_character_,
                                  `8` = NA_character_,
                                  `9` = NA_character_))

table(switzerland_data$born_in_country)
## 
##    No   Yes 
##  3867 13056
#Remove unique
unique(switzerland_data$educ_level)
## [1] "BA"    "No BA"
unique(switzerland_data$born_in_country)
## [1] "No"  "Yes" NA
switzerland_data <- switzerland_data %>% filter(!is.na(educ_level))
switzerland_data <- switzerland_data %>% filter(!is.na(born_in_country))

unique(switzerland_data$born_in_country)
## [1] "No"  "Yes"
table(switzerland_data$born_in_country)
## 
##    No   Yes 
##  3867 13056
#Tables
tab_dat <- switzerland_data

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

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.1764393
## [2,] 0.17578931 0.5957051
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##           [,1]      [,2]
## [1,]  881.1175  2985.882
## [2,] 2974.8825 10081.118
#Critical Value for Independence:
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
#Pearson’s chi-squared statistic
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 65.1218
#P-value
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 critical value is 3.84, and my observed Pearson’s chi-squared statistic of 65.122 is a much larger value than the critical value. This suggests that the difference between what was expected and what was observed was statistically significant. Hence, education level and if the person was born in the country has a significant relationship. In other words, whether a person is born in the country, it affects their levels of education.

Also, the p-value is 7.041e-16, which is much smaller than the significance level of 0.05. According to the difference between the critical value and Pearson’s chi-squared statistic, as well as the p-value, it suggests that we can reject the null hypothesis that the two variables are independent. Therefore education level and whether a person was born in the country has a significant association.

Task 2

netherlands_data <- ess %>%
    filter(cntry == "NL")

netherlands_data <- netherlands_data %>%
  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_))

table(netherlands_data$geo)
## 
## Rural Urban 
## 12681  5623
netherlands_data <- netherlands_data %>%
  mutate(gov = recode(as.character(gincdif), 
                      '1' = "Agree strongly", 
                      '2' = "Agree",
                      '3' = "Neither agree nor disagree", 
                      '4' = "Disagree", 
                      '5' = "Disagree strongly",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_))

table(netherlands_data$gov)
## 
##                      Agree             Agree strongly 
##                       7894                       2896 
##                   Disagree          Disagree strongly 
##                       3681                        543 
## Neither agree nor disagree 
##                       3142
#Remove unique values
unique(netherlands_data$geo)
## [1] "Urban" "Rural" NA
unique(netherlands_data$gov)
## [1] "Agree"                      "Disagree"                  
## [3] "Neither agree nor disagree" "Agree strongly"            
## [5] NA                           "Disagree strongly"
netherlands_data <- netherlands_data %>% filter(!is.na(geo))
netherlands_data <- netherlands_data %>% filter(!is.na(gov))

unique(netherlands_data$geo)
## [1] "Urban" "Rural"
table(netherlands_data$geo)
## 
## Rural Urban 
## 12574  5557
unique(netherlands_data$gov)
## [1] "Agree"                      "Disagree"                  
## [3] "Neither agree nor disagree" "Agree strongly"            
## [5] "Disagree strongly"
table(netherlands_data$gov)
## 
##                      Agree             Agree strongly 
##                       7886                       2889 
##                   Disagree          Disagree strongly 
##                       3676                        543 
## Neither agree nor disagree 
##                       3137
# Critical Value for Independence:
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
#Test-statistic
test_stat <- netherlands_data %>%
  specify(explanatory = geo, # change variable name for explanatory variable
          response = gov) %>% # change variable name for outcome of interest
  hypothesize(null = "independence") %>%
  calculate(stat = "Chisq") # replace in between quotation marks appropriate test statistic
print(test_stat$stat)
## X-squared 
##  8.176048
#Null distribution
null_distribution <- netherlands_data %>%
  specify(explanatory = geo,
          response = gov) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
  calculate(stat = "Chisq")

#p-value
p_val <- null_distribution %>%
  get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.182
#Visualize
null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided")
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.

null_distribution
## Response: gov (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 3.50 
##  2         2 2.17 
##  3         3 7.40 
##  4         4 5.20 
##  5         5 3.06 
##  6         6 9.51 
##  7         7 8.18 
##  8         8 0.887
##  9         9 1.94 
## 10        10 4.62 
## # ℹ 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 = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.

null_distribution
## Response: gov (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 3.50 
##  2         2 2.17 
##  3         3 7.40 
##  4         4 5.20 
##  5         5 3.06 
##  6         6 9.51 
##  7         7 8.18 
##  8         8 0.887
##  9         9 1.94 
## 10        10 4.62 
## # ℹ 990 more rows

A X-squared value of 8.18 is very close to the critical value of 3.841, indicating that the difference between the observed data and the expected data under the assumption of independence is not statistically significant. Therefore there is no statistically significant correlation between whether someone lives in a rural or urban area and whether the person favors the government to reduce income levels. In other words, the probability that a person favors the government to reduce income levels is similar across different living areas.

The p value is 0.18, which is greater than the significance level of 0.05. It suggests that we can not conclude that there is a relationship between living in an urban or rural area and a person’s opinion on whether the government should reduce income levels.

Furthermore, the visualisation of the null distribution reinforces the previous claim. This is because the chi-squared statistic falls within the confidence level, suggesting we fail to reject the null hypothesis, which implies that the two variables are independent.

Task 3

finland_data <- ess %>%
    filter(cntry == "FI")

finland_data <- finland_data %>%
  mutate(education = recode(as.character(edulvlb), 
                      '0' = "Not possible to harmonise into 5-level ISCED",
                      '1' = "Less than lower secondary education (ISCED 0-1)", 
                      '2' = "Lower secondary education completed (ISCED 2)",
                      '3' = "Upper secondary education completed (ISCED 3)", 
                      '4' = "Post-secondary non-tertiary education completed (ISCED 4)", 
                      '5' = "Tertiary education completed (ISCED 5-6)",
                      '55' = NA_character_,
                      '77' = NA_character_,
                      '88' = NA_character_,
                      '99' = NA_character_))

table(finland_data$education)
## 
##                                          113 
##                                         1312 
##                                          213 
##                                         1130 
##                                          313 
##                                          722 
##                                          323 
##                                         2942 
##                                          423 
##                                          671 
##                                          520 
##                                         1294 
##                                         5555 
##                                           11 
##                                          610 
##                                          988 
##                                          620 
##                                          564 
##                                          710 
##                                          185 
##                                          720 
##                                         1263 
##                                          800 
##                                          135 
##                                         8888 
##                                           10 
## Not possible to harmonise into 5-level ISCED 
##                                          192
finland_data <- finland_data %>%
  mutate(depressed = recode(as.character(fltdpr), 
                      '1' = "None or almost none of the time", 
                      '2' = "Some of the time",
                      '3' = "Most of the time", 
                      '4' = "All or almost all of the time", 
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_))

table(finland_data$depressed)
## 
##   All or almost all of the time                Most of the time 
##                              43                             106 
## None or almost none of the time                Some of the time 
##                            5026                             992
#Remove unique values
unique(finland_data$education)
##  [1] NA                                            
##  [2] "313"                                         
##  [3] "720"                                         
##  [4] "323"                                         
##  [5] "113"                                         
##  [6] "610"                                         
##  [7] "213"                                         
##  [8] "520"                                         
##  [9] "423"                                         
## [10] "710"                                         
## [11] "620"                                         
## [12] "800"                                         
## [13] "Not possible to harmonise into 5-level ISCED"
## [14] "5555"                                        
## [15] "8888"
unique(finland_data$depressed)
## [1] NA                                "None or almost none of the time"
## [3] "Some of the time"                "Most of the time"               
## [5] "All or almost all of the time"
finland_data <- finland_data %>% filter(!is.na(education))
finland_data <- finland_data %>% filter(!is.na(depressed))

unique(finland_data$education)
##  [1] "323"                                         
##  [2] "113"                                         
##  [3] "520"                                         
##  [4] "610"                                         
##  [5] "423"                                         
##  [6] "313"                                         
##  [7] "720"                                         
##  [8] "213"                                         
##  [9] "620"                                         
## [10] "800"                                         
## [11] "Not possible to harmonise into 5-level ISCED"
## [12] "8888"                                        
## [13] "710"                                         
## [14] "5555"
table(finland_data$education)
## 
##                                          113 
##                                          531 
##                                          213 
##                                          470 
##                                          313 
##                                          272 
##                                          323 
##                                         1091 
##                                          423 
##                                          288 
##                                          520 
##                                          504 
##                                         5555 
##                                            2 
##                                          610 
##                                          333 
##                                          620 
##                                          176 
##                                          710 
##                                           32 
##                                          720 
##                                          444 
##                                          800 
##                                           47 
##                                         8888 
##                                            2 
## Not possible to harmonise into 5-level ISCED 
##                                           84
unique(finland_data$depressed)
## [1] "None or almost none of the time" "Some of the time"               
## [3] "All or almost all of the time"   "Most of the time"
table(finland_data$depressed)
## 
##   All or almost all of the time                Most of the time 
##                              28                              75 
## None or almost none of the time                Some of the time 
##                            3533                             640
# Critical Value for Independence:
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
#Test-statistic
test_stat <- finland_data %>%
  specify(explanatory = education, # change variable name for explanatory variable
          response = depressed) %>% # change variable name for outcome of interest
  hypothesize(null = "independence") %>%
  calculate(stat = "Chisq") # replace in between quotation marks appropriate test statistic
print(test_stat$stat)
## X-squared 
##  72.77932
#Null distribution
null_distribution <- finland_data %>%
  specify(explanatory = education,
          response = depressed) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
  calculate(stat = "Chisq")

#p-value
p_val <- null_distribution %>%
  get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1    0.07
#Visualize
null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided")
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.

null_distribution
## Response: depressed (factor)
## Explanatory: education (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  45.9
##  2         2  46.0
##  3         3  33.8
##  4         4  31.0
##  5         5  35.0
##  6         6  41.8
##  7         7  31.4
##  8         8  95.8
##  9         9  24.3
## 10        10  29.8
## # ℹ 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 = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.

null_distribution
## Response: depressed (factor)
## Explanatory: education (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  45.9
##  2         2  46.0
##  3         3  33.8
##  4         4  31.0
##  5         5  35.0
##  6         6  41.8
##  7         7  31.4
##  8         8  95.8
##  9         9  24.3
## 10        10  29.8
## # ℹ 990 more rows

The variables that I might consider for my research question is the relationship between “edulvlb” (education level) and “fltdpr” (Felt depressed, how often past week). I was wondering if being more educated is correlated with being happier because education opens people to more opportunities to choose the life they want, or does higher education mean that they are under the pressure of society to complete a higher level of education.

The X-squared value of 72.8 is much larger than the critical value of 3.841. This suggests that the observed data and expected under the assumption of independence is statistically significant.

The p value of 0.07 is greater than the significance level of 0.05. It proposes that we can not conclude that there is a relationship between levels of education and if one has felt depressed in the past week.

The visualisation of the null distribution also showcases the claim that the two categorical variables are independent. This is because the chi-squared statistic falls within the confidence level, suggesting we fail to reject the null hypothesis that education level and feelings of depression are independent.