Install packages

packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer", 
              "fst", "viridis", "knitr", "kableExtra", "rmarkdown", "ggridges", "viridis", "questionr", "infer")
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] "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] "kableExtra"   "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] "rmarkdown"    "kableExtra"   "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"    "kableExtra"   "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"        
## 
## [[11]]
##  [1] "ggridges"     "rmarkdown"    "kableExtra"   "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] "questionr"    "ggridges"     "rmarkdown"    "kableExtra"   "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"        "questionr"    "ggridges"     "rmarkdown"    "kableExtra"  
##  [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"

Import ESS Data

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

Task 1

Recode numerous variables

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

  mutate(
    brncntr = case_when(
      brncntr == 1 ~ "Yes",  
      brncntr == 2 ~ "No",   
      brncntr %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(brncntr)
    ),

    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"
    ),
    
    gndr = case_when(
      gndr == 1 ~ "Male",
      gndr == 2 ~ "Female",
      gndr == 9 ~ NA_character_,
      TRUE ~ as.character(gndr)
    )
  )

Table of expected proportions, frequencies, and finding the critical value for independence

tab_data <- swiss_data
mytab <- table(tab_data$brncntr, tab_data$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
cat("\n")
ftab <- N * ptab
cat("Table of Expected Frequncies:\n")
## Table of Expected Frequncies:
print(ftab)
##           [,1]      [,2]
## [1,]  881.1175  2985.882
## [2,] 2974.8825 10081.118
cat("\n")
alpha <- 0.05
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841

A Critical Value of 3.841 means that if the Chi-squared test stat exceeds 3.841, then the null hypothesis is rejected at significance level: 0.05. This means if the result is >3.841, there is a significant association between being born in the country and education level in the Swiss dataset.

Pearson’s chi-squared statistic and the p-value

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 Pearson chi-squared statistic is 65.1218, much larger than the Critical Value of 3.841, meaning there is a significant association between being born in the country and education level in the Swiss dataset. This also means that the probability of being born in the country is not uniform across education levels in Switzerland.

The chi-squared test and p-value being extremely close to 0 and small means that we can reject the null hypothesis that the two variables are independent (hence, they are dependent on each other to some degree).

Overall, the main takeaway is that in Switzerland, there is a strong association between being born in the country and education level. This may hint that citizenry in Switzerland (like most countries) is extremely important for education.

Task 2

Recode variables domicil and gincdif

nether_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_,
  )
  )
nether_data <- ess %>%
  filter(cntry == "NL") %>%
mutate(
  gincdif = case_when(
    gincdif == 1 ~ "Strongly agree",
    gincdif == 2 ~ "Agree",
    gincdif == 3 ~ "Neither agree or disagree",
    gincdif == 4 ~ "Disagree",
    gincdif == 5 ~ "Strongly disagree",
    gincdif %in% c(7, 8, 9) ~ NA_character_,
    TRUE ~ as.character(gincdif),
  )
)
  nether_data <- nether_data %>%
    filter(!is.na(gincdif))

Calculate test statistic

test_stat <- nether_data %>%
  specify(explanatory = gincdif,
          response = domicil) %>%
  hypothesize(null = "independence") %>%
  calculate(stat = "F")
print(test_stat$stat)
## [1] 4.832131

I ended up using ANOVA or “F” to calculate the test statistic here. The higher the f value, or 4.83 in this case, the higher the difference between the sample means.

Simulate the null distribution

null_distribution <- nether_data %>%
  specify(explanatory = gincdif,
          response = domicil) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "F")

Calculate the p-value of the 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

There is strong reasoning to reject the null, since the p value is “0” (extremely close to 0).

Visualize + CI

ci <- 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 = ci)
## Warning: F usually corresponds to right-tailed tests. Proceed with caution.

null_distribution
## Response: domicil (numeric)
## Explanatory: gincdif (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 0.305
##  2         2 2.37 
##  3         3 1.04 
##  4         4 0.872
##  5         5 0.449
##  6         6 2.94 
##  7         7 0.893
##  8         8 1.60 
##  9         9 2.99 
## 10        10 1.16 
## # ℹ 990 more rows

After conducting the 4 steps, we see that we have good reason to reject the null hypothesis. The p-value is essentially 0, and the observed test stat is beyond the null distribution whilst the confidence interval is within the null distribution. There is nothing that suggests the null hypothesis should not be rejected, according to frequentist hypothesis testing.

Task 3

Basic research question: Does how interested people are in politics influence whether or not they believe it’s important that the government is strong and ensures safety in Russia?

Recode variables polintr and ipstrgv

rus_data <- ess %>%
  filter(cntry == "RU") %>%
  mutate(govstr = recode(as.character(ipstrgv),
                     `1` = "Very much like me",
                     `2` = "Like me",
                     `3` = "Somewhat like me",
                     `4` = "A little like me",
                     `5` = "Not like me",
                     `6` = "Not like me at all",
                     `7` = NA_character_,
                     `8` = NA_character_,
                     `9` = NA_character_,
  )
  )
rus_data <- ess %>%
  filter(cntry == "RU") %>%
mutate(
  polintr = case_when(
    polintr == 1 ~ "Very interested",
    polintr == 2 ~ "Quite interested",
    polintr == 3 ~ "Hardly interested",
    polintr == 4 ~ "Not interested at all",
    polintr %in% c(7, 8, 9) ~ NA_character_,
    TRUE ~ as.character(polintr),
  )
)
  rus_data <- rus_data %>%
    filter(!is.na(polintr))

Calculate test statistic

test_stat2 <- rus_data %>%
  specify(explanatory = polintr,
          response = ipstrgv) %>%
  hypothesize(null = "independence") %>%
  calculate(stat = "F")
print(test_stat2$stat)
## [1] 33.78034

F value of 33.78 suggests the difference between sample means is significant.

Simulate the null distribution

null_distribution2 <- rus_data %>%
  specify(explanatory = polintr,
          response = ipstrgv) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "F")

Calculate the p-value of the sample

p_val <- null_distribution2 %>%
  get_pvalue(obs_stat = test_stat2, 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 is 0 again, once again suggesting that it is reasonable to reject the null hypothesis.

Visualize + CI

ci <- null_distribution2 %>%
  get_confidence_interval(level = 0.95, type = "percentile")

null_distribution2 %>%
  visualize() +
  shade_p_value(obs_stat = test_stat2, direction = "two-sided") +
  shade_confidence_interval(endpoints = ci)
## Warning: F usually corresponds to right-tailed tests. Proceed with caution.

null_distribution2
## Response: ipstrgv (numeric)
## Explanatory: polintr (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 0.505
##  2         2 0.299
##  3         3 0.442
##  4         4 0.644
##  5         5 0.775
##  6         6 0.806
##  7         7 3.02 
##  8         8 1.42 
##  9         9 2.12 
## 10        10 0.770
## # ℹ 990 more rows

In this case again, we can completely reject the null hypothesis as the p-value is 0, the f value is extremely high, and the CI falls mostly within the null distribution. Of course, all according to frequntist hypothesis testing. The result is thus statistically significant and there is significant relationship between the explanatory variable (polintr) and outcome variable (ipstrgv).