packages <- c("tidyverse", "infer", "fst") # add any you need here


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"
setwd("~/Desktop/SOC202 H1/Coding Tut 1/SOC202_Project_MarcoHuang/Huang_Marco_Project 202")
getwd()
## [1] "/Users/marcohuang/Desktop/SOC202 H1/Coding Tut 1/SOC202_Project_MarcoHuang/Huang_Marco_Project 202"
ess <- read_fst("All-ESS-Data.fst")
SWL_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(clsprty)  
    ),
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),

    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"
    ),
    
    # Recoding gender
    gndr = case_when(
      gndr == 1 ~ "Male",
      gndr == 2 ~ "Female",
      gndr == 9 ~ NA_character_,
      TRUE ~ as.character(gndr)
    )
  )
#Task 1
unique(SWL_data$gndr)
## [1] "Female" "Male"   NA
unique(SWL_data$brncntr)
## [1] "No"  "Yes" NA
SWL_data <- SWL_data %>% filter(!is.na(brncntr))
SWL_data <- SWL_data %>% filter(!is.na(trstplt))
SWL_data <- SWL_data %>% filter(!is.na(educ_level))

unique(SWL_data$brncntr)
## [1] "No"  "Yes"
table(SWL_data$brncntr)
## 
##    No   Yes 
##  3570 12841
tab_dat <- SWL_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.05018556 0.1673515
## [2,] 0.18051337 0.6019496
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##           [,1]     [,2]
## [1,]  823.5951 2746.405
## [2,] 2962.4049 9878.595
alpha <- 0.05 
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841

The critical value of 3.841 tells us that there is a strong evidence proving a relationship in related to born in country and the level of education one can achieve.

#Pearson Chi-squared value
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 75.4503
#P value for switzerland
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 = 75.45, df = 1, p-value < 2.2e-16

The result of Chisq test suggests the probability of education level vary from the different level of born in country.On the other hand, a p value equal 0 tells us that both variables here are independent and strongly relative to each other.

#TASK 2
NL_data <- ess %>%
  filter(cntry == "NL")
NL_data <- NL_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(NL_data$geo)
## 
## Rural Urban 
## 12681  5623
NL_data <- ess %>%
  filter(cntry == "NL") %>%
  mutate(
    gincdif = case_when(
      gincdif == 1 ~ "Agree", 
      gincdif == 2 ~ "Agree", 
      gincdif == 4 ~ "Disagree",
      gincdif == 5 ~ "Disagree",
      gincdif %in% c(3, 7, 8, 9) ~ NA_character_,  # Handle other specific cases where you want to set it as NA
      TRUE ~ as.character(gincdif)  # Keep other values as-is but ensure they are characters
    ),
    attitude_level = case_when(
      essround < 5 & gincdif == 1 ~ "Agree",
      essround >= 5 & gincdif > 2 ~ "Agree",
      TRUE ~ "Disagree"
    ),
  )
NL_data <- NL_data %>% filter(!is.na(attitude_level))
unique(NL_data$attitude_level)
## [1] "Disagree" "Agree"
table(NL_data$attitude_level)
## 
##    Agree Disagree 
##     8511     9818
test_stat <- NL_data %>%
  specify(explanatory = attitude_level, 
          response = domicil) %>% 
  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 "Agree" - "Disagree", or divided in the order "Agree" / "Disagree" for
## ratio-based statistics. To specify this order yourself, supply `order =
## c("Agree", "Disagree")` to the calculate() function.
print(test_stat$stat)
##         t 
## 0.6568044

Using the T-test, the result of 0.65 shows an insignificant relation between the place of residence in term of people’s attitude toward whether or not government should reduce difference in income level. It infers us that there might be other variables more valid to explain the relationship.

null_distribution <- NL_data %>%
  specify(explanatory = attitude_level,
          response = domicil) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
  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 "Agree" - "Disagree", or divided in the order "Agree" / "Disagree" for
## ratio-based statistics. To specify this order yourself, supply `order =
## c("Agree", "Disagree")` to the calculate() function.
p_val <- null_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1    0.51

Usually the p value has be to closer to 0 or less than 0.5 to prove values are significant. However, a p value of 0.52 here indicates that null hypothesis might be wrong since they are not statistically significant.

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

null_distribution
## Response: domicil (numeric)
## Explanatory: attitude_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1 -1.55  
##  2         2 -0.0177
##  3         3  1.95  
##  4         4 -0.162 
##  5         5  0.705 
##  6         6 -1.35  
##  7         7 -1.38  
##  8         8 -0.355 
##  9         9  0.332 
## 10        10 -0.235 
## # ℹ 990 more rows
#TASK3

For Task 3. Currently, a research question I am thinking of would be discovering relationship between place of residence and level of education in United Kingdom. The variables here are “domicil” and “edulvla”, “edulvlb” (including all rounds).

UK_data <- ess %>%
  filter(cntry == "GB")
UK_data <- UK_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(UK_data$geo)
## 
## Rural Urban 
## 14550  6376
UK_data <- ess %>%
  filter(cntry == "GB") %>%
  mutate(
    clsprty = case_when(
      clsprty == 1 ~ "Yes", 
      clsprty == 2 ~ "No",   
      clsprty %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(clsprty)  
    ),
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    UKeduc_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "No BA"
    ))
    
UK_data <- UK_data %>% filter(!is.na(UKeduc_level))
unique(UK_data$UKeduc_level)
## [1] "BA"    "No BA"
table(UK_data$UKeduc_level)
## 
##    BA No BA 
##  6116 14863
test_stat <- UK_data %>%
  specify(explanatory = UKeduc_level, 
          response = domicil) %>% 
  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(test_stat$stat)
##         t 
## -2.852996

A negative t value implies that the sample mean might be less than the hypothesized mean. This would be evidence against the null hypothesis as well as suggesting significant relationship between these two variables.

null_distribution <- UK_data %>%
  specify(explanatory = UKeduc_level,
          response = domicil) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
  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.
p_val <- null_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.002

It rejects the null hypothesis because of the p value being 0, suggesting that there are signicant relationship between them. In the meantime, the visualization of the extreme red shaded regions also supports to rejection of null since it is one sided (to the left) extreme.

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

null_distribution
## Response: domicil (numeric)
## Explanatory: UKeduc_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1 -0.472 
##  2         2 -1.02  
##  3         3  0.943 
##  4         4  0.277 
##  5         5 -0.161 
##  6         6 -0.0200
##  7         7 -0.566 
##  8         8  0.120 
##  9         9 -0.145 
## 10        10  1.62  
## # ℹ 990 more rows