Setting Up Environment

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"
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"
    ),
    
  )
#Double Check for NAs
unique(switzerland_data$educ_level)
## [1] "BA"    "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))

table(switzerland_data$brncntr) 
## 
##    No   Yes 
##  3867 13056
#Create Table of Expected Proportions
table_dat <- switzerland_data
mytab <- table(table_dat$brncntr, table_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
#Create Table of Expected Frequencies
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
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
#Pearsons Chi-squared statistic and 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 set critical value was calculated as 3.841; if the computed chi-squared statistic exceeds this value, we can reject the null hypothesis at the 0.05 level, indicating a statistically significant correlation between our variables of education level and country of birth within the data set. The calculated chi-squared statistic was 65.1218, significantly larger than the critical value of 3.841. One could conclude that being born in the country of interest is strongly statistically associated with having a higher degree of education, as the observed data deviates from what would be expected under the assumption of independence. We know a p-value less than the designated threshold (<0.05) rejects the null; the calculated p-value is 7.041e-16. The exceedingly small p-value indicates substantial evidence to refute the notion that the two variables are independent. The value suggests a significant association between the variables brncntr and educ_level. The main takeaway from this task was to learn a) to do chi-square long-form calculations and to understand the relationship between the critical value, the p-value, and the resulting value of Pearson’s chi-squared test.

Task 2

netherlands_data <- ess %>%
  filter(cntry == "NL") %>%
  
  mutate(
    gincdif = case_when(
      gincdif %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(gincdif)
    ),
    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)

#Double Checking NAs
unique(netherlands_data$gincdif)
## [1]  2  4  3  1 NA  5
unique(netherlands_data$domicil)
## [1] "Urban" "Rural" NA
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
#Step 1: Calculate Test Statistic of Sample
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
#Step 2:Simulate the null distribution
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.
#Step 3: Calculate the p-value of sample
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
#Step 4: Visualize
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 -1.13  
##  2         2 -1.28  
##  3         3  0.181 
##  4         4 -0.182 
##  5         5  0.626 
##  6         6 -0.711 
##  7         7 -0.237 
##  8         8 -0.557 
##  9         9 -0.724 
## 10        10  0.0137
## # ℹ 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 -1.13  
##  2         2 -1.28  
##  3         3  0.181 
##  4         4 -0.182 
##  5         5  0.626 
##  6         6 -0.711 
##  7         7 -0.237 
##  8         8 -0.557 
##  9         9 -0.724 
## 10        10  0.0137
## # ℹ 990 more rows

We learned that the t-statistic represents the discrepancy 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. Regardless of its sign, a larger absolute value of t provides more substantial evidence against the null hypothesis. From Task 2 calculations, we have a t-stat of 3.013806, which is insignificant; it is simply not large enough. Therefore, we do not have strong evidence against the null hypothesis from this t-statistic. This was an excellent setup for future coding. I was following the Steps on RPubs with a lot of confusion at first, but then I figured it out. I initially believed when the instructions said, “For gincdif, you must recode for the five categories (i.e., cannot keep as numeric),” I had to change the numbers to labels such as “Agree” or “Disagree,” so I wasted a lot of time wondering why that wasn’t working however I realized soon enough that I must put TRUE:~ as.character(gincfel) as well as netherlands_data\(gincdif <- as.numeric(netherlands_data\)gincdif). I also checked the classes after these steps using class(netherlands_data$gincdef) to ensure I had the proper setup for the upcoming steps (referring to the Week 6 slides was very helpful).

Task 3 Research Question: How does one’s gender (gndr) [explanatory variable] affect how one values the importance of following tradition and customs (imptrad) [outcome variable] in Italy?

italy_data <- ess %>%
  filter(cntry == "IT") %>%
  mutate(
    imptrad = case_when(
      imptrad %in% c(7, 8, 9) ~ NA_character_,  
      TRUE ~ as.character(imptrad)  
    ),
 gndr = case_when(
      gndr == 1 ~ "Male",
      gndr == 2 ~ "Female",
      gndr == 9 ~ NA_character_,
      TRUE ~ as.character(gndr)
    )
  )
italy_data$imptrad <- as.numeric(italy_data$imptrad)
unique(italy_data$imptrad)
## [1] NA  1  4  3  2  5  6
unique(italy_data$gndr)
## [1] "Male"   "Female" NA
italy_data <- italy_data %>% filter(!is.na(imptrad))
italy_data <- italy_data %>% filter(!is.na(gndr))

table(italy_data$gndr)
## 
## Female   Male 
##   4571   4191
table(italy_data$imptrad)
## 
##    1    2    3    4    5    6 
## 2342 2995 2124  921  262  118
class(italy_data$gndr) 
## [1] "character"
class(italy_data$imptrad)
## [1] "numeric"
#Step 1: Calculate Test Statistic of sample
trad_stat <- italy_data %>%
  specify(explanatory = gndr,
          response = imptrad)%>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "t") # As imptrad is numeric, gndr is categorical (two categories) use two sample T test
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "Female" - "Male", or divided in the order "Female" / "Male" for
## ratio-based statistics. To specify this order yourself, supply `order =
## c("Female", "Male")` to the calculate() function.
print(trad_stat$stat)
##         t 
## -6.779073
#Step 2:Simulate the null distribution
null_trad <- italy_data %>%
  specify(explanatory = gndr,
          response = imptrad)%>%
  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 "Female" - "Male", or divided in the order "Female" / "Male" for
## ratio-based statistics. To specify this order yourself, supply `order =
## c("Female", "Male")` to the calculate() function.
#Step 3: Calculate the p-value of sample
p_val <- null_trad %>%
  get_pvalue(obs_stat = trad_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
#Step 4: Visualize 
null_trad %>%
  visualize() +
  shade_p_value(obs_stat = trad_stat, direction = "two-sided")

null_trad
## Response: imptrad (numeric)
## Explanatory: gndr (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1 -0.421 
##  2         2 -1.50  
##  3         3 -0.0466
##  4         4  0.365 
##  5         5 -1.78  
##  6         6 -1.00  
##  7         7  0.122 
##  8         8 -0.683 
##  9         9 -0.645 
## 10        10 -1.52  
## # ℹ 990 more rows
conf_int <- null_trad %>%
  get_confidence_interval(level = 0.95, type = "percentile")

null_trad %>%
  visualize() +
  shade_p_value(obs_stat = trad_stat, direction = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)

null_trad
## Response: imptrad (numeric)
## Explanatory: gndr (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate    stat
##        <int>   <dbl>
##  1         1 -0.421 
##  2         2 -1.50  
##  3         3 -0.0466
##  4         4  0.365 
##  5         5 -1.78  
##  6         6 -1.00  
##  7         7  0.122 
##  8         8 -0.683 
##  9         9 -0.645 
## 10        10 -1.52  
## # ℹ 990 more rows

Since we know 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. In investigating the t-stat in Task 3, you see that the magnitude of t is relatively large (despite being negative) around -6.78. So, we have a decent amount of evidence against the null hypothesis; therefore, there is a difference between the two genders regarding the importance of traditions and customs in Italy. We know a p-value less than the designated threshold (<0.05) rejects the null; we could conclude from our p-value of 0 that the null could be rejected. My main takeaway from this task was patience. As always, I had difficulty deciding which variables and country to pick. I had to ensure I used the proper test for my variables; this is where the class function was very beneficial. I took too long on this and am still not confident, as my p-value of 0 seems off. However, I now understand which test statistic to use for which variable.