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.3     ✔ 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("/Users/luoyujian/Downloads")
library(fst)
ess <- read_fst("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$brncntr)
## [1] "No"  "Yes" NA
switzerland_data <- switzerland_data %>% filter(!is.na(brncntr))
switzerland_data <- switzerland_data %>% filter(!is.na(educ_level))

unique(switzerland_data$brncntr)
## [1] "No"  "Yes"
table(switzerland_data$brncntr)
## 
##    No   Yes 
##  3867 13056
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)

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
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 that you compute (from the chisq.test function) exceeds 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 the variable of born in country or not and the variable of education level in the dataset.
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 65.1218
#Comparison to the critical value: The observed X-squared value is much larger than this critical value of 3.841.

#Interpretation: The difference between our observed data and what we’d expect under the assumption of independence is statistically significant. Thus, there is a statistically significant association between the variable of born in country and the variable of one’s educational level. This means that the probability of born in country is not the same across different education levels.
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 result of p-value is very close to 0, which means that we reject the null hypothesis, so that is to say there’s strong evidence to suggest that there’s a significant association between "born in country" and "education level" in mytab.
#Task 2:
netherlands_data <- ess %>%
  
  filter(cntry == "NL") %>%
  
  
  mutate(
    gincdif = case_when(
      
      gincdif %in% c(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
    ),
   
    
   
    domicil = case_when(
      domicil %in% c(1, 2, 3) ~ "Urban",
      domicil %in% c(4, 5) ~ "Rural",
      domicil %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(domicil)
    )
  )
netherlands_data$gincdif <- as.numeric(netherlands_data$gincdif)

unique(netherlands_data$gincdif)
## [1]  2  4  3  1 NA  5
netherlands_data <- netherlands_data %>% filter(!is.na(gincdif))

netherlands_data <- netherlands_data %>% filter(!is.na(domicil))

unique(netherlands_data$gincdif)
## [1] 2 4 3 1 5
table(netherlands_data$gincdif)
## 
##    1    2    3    4    5 
## 2889 7886 3137 3676  543
table(netherlands_data$domicil)
## 
## Rural Urban 
##  7931 10200
class(netherlands_data$gincdif)
## [1] "numeric"
test_stat <- netherlands_data %>%
  specify(explanatory = domicil, 
          response = gincdif) %>% 
  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 "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)
##        t 
## 3.013806
#Interpreting: The t-statistic measures the difference between the observed sample mean and the population mean (or another sample mean, in the case of two-sample tests) in units of standard error. The larger the magnitude of t (regardless of the sign), the greater the evidence against the null hypothesis. 3.013806 is a relatively small, which indicates that we don't have a strong evidence against the null hypothesis.
null_distribution <- netherlands_data %>%
  specify(explanatory = domicil,
          response = gincdif) %>%
  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 "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_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "two-sided") 

p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.004
null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided")

null_distribution
## Response: gincdif (numeric)
## Explanatory: domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1 -0.794 
##  2         2 -1.01  
##  3         3 -0.139 
##  4         4 -1.79  
##  5         5  0.403 
##  6         6 -1.27  
##  7         7  1.42  
##  8         8 -0.279 
##  9         9 -0.321 
## 10        10 -0.0560
## # ℹ 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)

null_distribution
## Response: gincdif (numeric)
## Explanatory: domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1 -0.794 
##  2         2 -1.01  
##  3         3 -0.139 
##  4         4 -1.79  
##  5         5  0.403 
##  6         6 -1.27  
##  7         7  1.42  
##  8         8 -0.279 
##  9         9 -0.321 
## 10        10 -0.0560
## # ℹ 990 more rows
#Main Takeaway: I have a deeper understanding of the t-test by using Rstudio instead of the calcluating by hand.
#Task 3:
#Research Question: How does the the frequency of finding that one's partner or family gets fed up with the pressure of your job related to the stress of the society on the happiness of people in Spain.

spain_data <- ess %>%
 
  filter(cntry == "ES") %>%
  
 
  mutate(
    happy = case_when(
      
      happy %in% c(77, 88, 99) ~ NA_character_,  
      TRUE ~ as.character(happy)  
    ),
   
    
    
    pfmfdjba = case_when(
      pfmfdjba %in% c(1, 2, 3) ~ "Sometimes",
      pfmfdjba %in% c(4, 5) ~ "Always",
      pfmfdjba %in% c(6, 7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(pfmfdjba)
    )
  )
spain_data$happy <- as.numeric(spain_data$happy)

unique(spain_data$happy)
##  [1]  7  8  6  5 10  4  2  9 NA  3  0  1
spain_data <- spain_data %>% filter(!is.na(happy))

spain_data <- spain_data %>% filter(!is.na(pfmfdjba))

unique(spain_data$happy)
##  [1]  8  7 10  6  9  2  5  4  3  1  0
table(spain_data$happy)
## 
##   0   1   2   3   4   5   6   7   8   9  10 
##  13  12  23  35  33 141 164 458 621 299 193
table(spain_data$pfmfdjba)
## 
##    Always Sometimes 
##       243      1749
test_stat <- spain_data %>%
  specify(explanatory = pfmfdjba, 
          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 "Always" - "Sometimes", or divided in the order "Always" / "Sometimes"
## for ratio-based statistics. To specify this order yourself, supply `order =
## c("Always", "Sometimes")` to the calculate() function.
print(test_stat$stat)
##         t 
## -6.472163
null_distribution <- spain_data %>%
  specify(explanatory = pfmfdjba,
          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 "Always" - "Sometimes", or divided in the order "Always" / "Sometimes"
## for ratio-based statistics. To specify this order yourself, supply `order =
## c("Always", "Sometimes")` to the calculate() function.
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")

null_distribution
## Response: happy (numeric)
## Explanatory: pfmfdjba (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1  0.0442
##  2         2 -0.145 
##  3         3 -0.974 
##  4         4 -0.812 
##  5         5  0.244 
##  6         6 -0.698 
##  7         7  0.792 
##  8         8  0.660 
##  9         9  0.129 
## 10        10 -0.476 
## # ℹ 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)

null_distribution
## Response: happy (numeric)
## Explanatory: pfmfdjba (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1  0.0442
##  2         2 -0.145 
##  3         3 -0.974 
##  4         4 -0.812 
##  5         5  0.244 
##  6         6 -0.698 
##  7         7  0.792 
##  8         8  0.660 
##  9         9  0.129 
## 10        10 -0.476 
## # ℹ 990 more rows
# Takeaway: Thorough understanind in a completely new senario.