packages <- c("tidyverse", "infer", "fst")
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
## [[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)

ess <- read_fst("/Users/jasminevvvvvvv/Desktop/UT/SOC202/Homework/All-ESS-Data.fst")

##Task 1

switzerland_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"
    )
  )

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

mytab <- table(tab_dat$brncntr, 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
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_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

Task 2

netherlands_data <- ess %>%
  filter(cntry == "NL") %>%
  
  mutate(
    gincdif = case_when(
      gincdif == 1 ~ "Strongly agree",  
      gincdif == 2 ~ "Agree",  
      gincdif == 3 ~ "Neither agree nor disagree",  
      gincdif == 4 ~ "Disagree",
      gincdif == 5 ~ "Strongly disagree",
      gincdif %in% c(7, 8, 9) ~ NA_character_,  
      TRUE ~ as.character(gincdif)  
    ),
    
    
    domicila = case_when(
      essround < 5 & domicil == 55 ~ NA_real_,
      TRUE ~ domicil
    ),
    
    
    domicilb = case_when(
      essround >= 5 & domicil == 5555 ~ NA_real_,
      TRUE ~ domicil
    ),
    
   
    domicil = case_when(
      essround < 5 & domicila == 5 ~ "BA",
      essround >= 5 & domicilb > 600 ~ "BA",
      TRUE ~ "No BA"
    )
  )

test_stat <- netherlands_data %>%
  specify(explanatory = domicil, 
          response = gincdif,) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq")
## Warning: Removed 173 rows containing missing values.
print(test_stat$stat)
## X-squared 
##  4.256857
null_distribution <- netherlands_data %>%
  specify(explanatory = domicil,
          response = gincdif) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "chisq")
## Warning: Removed 173 rows containing missing values.
p_val <- null_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "two-sided") 

p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.762
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.

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: gincdif (factor)
## Explanatory: domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 1.99 
##  2         2 1.54 
##  3         3 3.50 
##  4         4 0.550
##  5         5 5.19 
##  6         6 3.59 
##  7         7 5.55 
##  8         8 1.28 
##  9         9 4.07 
## 10        10 4.31 
## # ℹ 990 more rows

Task 3

The research question I would like to consider is the relationship between people from Norway’s education level and their network usage.

norway_data <- ess %>%
  filter(cntry == "NO") %>%
  mutate( 
 netuse = case_when(
      netuse == 1 ~ "Always",  
      netuse == 2 ~ "Often",  
      netuse == 3 ~ "Normal",  
      netuse == 4 ~ "Seldom",
      netuse == 5 ~ "Never",
      netuse %in% c(7, 8, 9) ~ NA_character_,  
      TRUE ~ as.character(netuse)  
    ),
    
    
    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"
    )
  )

unique(norway_data$educ_level)
## [1] "No BA" "BA"
table(norway_data$educ_level)
## 
##    BA No BA 
##  5722 10343
unique(norway_data$brncntr)
## [1] 1 2 8 7 9
table(norway_data$brncntr)
## 
##     1     2     7     8     9 
## 14534  1506     1     1    23
norway_data <- norway_data %>% filter(!is.na(netuse))
norway_data <- norway_data %>% filter(!is.na(educ_level))

test_stat <- norway_data %>%
  specify(explanatory = educ_level, 
          response = netuse,) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq")

print(test_stat$stat)
## X-squared 
##  376.3574
null_distribution <- norway_data %>%
  specify(explanatory = educ_level,
          response = netuse) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "chisq")

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
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.

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: netuse (factor)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 11.5 
##  2         2 19.4 
##  3         3  7.55
##  4         4  4.40
##  5         5  4.56
##  6         6  3.34
##  7         7  6.64
##  8         8  9.06
##  9         9  6.12
## 10        10  8.66
## # ℹ 990 more rows

The p-value is reported as 0, which is typically an indication of a very small p-value.Simulation-based null distribution is obviously right-tailed, and could be considered as the observed test statistic is larger than what would be expected under the null hypothesis of independence. The results suggest a significant relationship between education level and network usage in the studied population from Norway, which is the lower the education is the more often people use their network