Homework 7 (2.5%) due Nov. 13

Submit on Quercus using assignment tab – not on the discussion board. Make sure to provide both your markdown file and R pubs link. If you do not submit both, you will be penalized 1 pt. out of the 2.5 total.

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"
ess <- read_fst("All-ESS-Data.fst")

Task 1

Set up the calculations for an exploration of educ_level (as BA, No BA) and brncntr (recoded as yes/no *shown in tutorial 4) for Switzerland. Using the steps outlined in the tutorial, first generate the tables of expected proportions and frequencies. Determine and interpret the critical value for independence. Finally, determine and interpret both the Pearson’s chi-squared statistic and the p-value. Discuss main takeaways.

switzerland_data <- ess %>%

  filter(cntry == "CH") %>%
  
   mutate(brncntr = recode(brncntr,
                                  `1` = "Yes",
                                  `2` = "No",
                                  `7` = NA_character_,
                                  `8` = NA_character_,
                                  `9` = NA_character_),
        
    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"
    ),
            )
tab_dat <- switzerland_data

swiss_mytab <- table(tab_dat$brncntr, tab_dat$educ_level)

rsums <- rowSums(swiss_mytab)

csums <- colSums(swiss_mytab)

N <- sum(swiss_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 
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841
test_stat <- sum((swiss_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: We previously calculated a critical value of 3.841. Our observed X-squared value is much larger than this critical value.

#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 whether one is born in country and one’s educational level. This means that the probability of one’s status of born in the 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(swiss_mytab, correct = F))
## 
##  Pearson's Chi-squared test
## 
## data:  swiss_mytab
## X-squared = 65.122, df = 1, p-value = 7.041e-16

#p-value = 7.041e-16: This is another representation of the p-value in scientific notation because it’s extremely close to 0.

#The chi-squared test tells us if two categorical variables are independent or if they are associated in some manner. In our test:

#The extremely small p-value (essentially 0) means that we reject the null hypothesis that the two variables are independent of each other. In other words, there’s strong evidence to suggest that there’s a significant association between whether one is born in country and one’s educational level.

#The large chi-squared statistic of 65.122 further reinforces this point. If the two variables were independent, we’d expect a chi-squared statistic closer to 0.

#Takeaways: I really see the importance of p-value and chi-squared test when determine whether or not we would reject the null hypothesis, especially p-value (whether or not the p-value > 0.05, if p-value > 0.05 we would reject, if not we can’t.)

Task 2

Using the infer package and following the 4 steps outlined in the tutorial and during the lecture, conduct and visualize the hypothesis testing for domicil (recoded as urban/rural – see tutorial 4) and gincdif (Government should reduce differences in income levels) for the country of Netherlands. For gincdif, you must recode for the five categories (i.e, cannot keep as numeric).

Make decision over appropriate test given table provided during lecture. After conducting the 4 steps, interpret all the output and discuss your takeaways.

netherlands_data <- ess %>%
 
  filter(cntry == "NL") %>%
  
  mutate(geo = recode(as.character(domicil), 
                      '1' = "Urban", 
                      '2' = "Peri-Urban", 
                      '3' = "Rural", 
                      '4' = "Rural", 
                      '5' = "Rural",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_),

   gincdif = recode(as.character(gincdif),
                      '1' = "Agree strongly", 
                      '2' = "Agree", 
                      '3' = "Neither agree nor disagree", 
                      '4' = "Disagree", 
                      '5' = "Disagree strongly",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_ ),
  )
test_stat <- netherlands_data %>%
  specify(explanatory = geo, 
          response = gincdif) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq") 
## Warning: Removed 198 rows containing missing values.
print(test_stat$stat)
## X-squared 
##  24.81544
nl_null_distribution <- netherlands_data %>%
  specify(explanatory = geo,
          response = gincdif) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "chisq")
## Warning: Removed 198 rows containing missing values.
nl_p_val <- nl_null_distribution %>% # replace name here if you assigned something other than null_distribution above
  get_pvalue(obs_stat = test_stat, direction = "two-sided") # would only replace test_stat if assigned another name in Step 1

nl_p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.004
nl_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.

nl_null_distribution
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  8.22
##  2         2  6.90
##  3         3  5.42
##  4         4 15.7 
##  5         5 10.8 
##  6         6  5.27
##  7         7  8.01
##  8         8  2.83
##  9         9  2.21
## 10        10 17.4 
## # ℹ 990 more rows
conf_int <- nl_null_distribution %>%
  get_confidence_interval(level = 0.95, type = "percentile")


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

nl_null_distribution
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  8.22
##  2         2  6.90
##  3         3  5.42
##  4         4 15.7 
##  5         5 10.8 
##  6         6  5.27
##  7         7  8.01
##  8         8  2.83
##  9         9  2.21
## 10        10 17.4 
## # ℹ 990 more rows

#T-statistic: 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. A t-statistic of 24.815 is quite large, indicating a significant difference in whether Government should reduce differences in income levels between those live in urban and rural area. It suggests that the mean level of government should reduce differences in income is different for the two groups.

#P-value: A p-value of 0 which is smaller than 0.05 means we can reject the null hypothesis with strong evidence.

#Visualization: Visualizes the null distribution alongside the observed test statistic (the red line), indicating here clear evidence, under assumptions of frequentist hypothesis testing, to reject the null.

#Appropriate test: According to the lecture slides, in this case both variables are categorical variable and with three or more categories, that would give us chi-square test of independence as the most appropriate test.

#Takeaways: Both variables are categorical variables with two or more variables fits chi-square test, and in this case we could change numeric variable to category variable in order to proceed a chi-square test.

Task 3

First, talk about a research question you would like to consider, which identifies a main relationship between an explanatory variable and an outcome variable. Using the infer package and following the 4 steps outlined in the tutorial and during the lecture, conduct and visualize the hypothesis testing for your variables based on your research question. After conducting the 4 steps, interpret all the output and discuss your takeaways.

Research Question: How does the education level of individuals correlate with the type of organization they work or have worked for in France?

france_data <- ess %>%

  filter(cntry == "FR") %>%
 
  mutate(
     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"
    ),
     
      tporgwk= recode(as.character(tporgwk),
                      '1' = "Government", 
                      '2' = "Other public sector", 
                      '3' = "State owned enterprise", 
                      '4' = "Private firm", 
                      '5' = "Self employed",
                      '6' = NA_character_,
                      '66' = NA_character_,
                      '77' = NA_character_,
                      '88' = NA_character_,
                      '99' = NA_character_ ),
    
    
    
  )
fr_stat <- france_data %>%
  specify(explanatory = educ_level, 
          response = tporgwk) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq") 
## Warning: Removed 6595 rows containing missing values.
print(fr_stat$stat)
## X-squared 
##   371.071
fr_null_distribution <- france_data %>%
  specify(explanatory = educ_level,
          response = tporgwk) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "chisq")
## Warning: Removed 6595 rows containing missing values.
fr_p_val <- fr_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.
fr_p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0
fr_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.

fr_null_distribution
## Response: tporgwk (factor)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  4.52
##  2         2 11.9 
##  3         3  7.50
##  4         4  4.95
##  5         5  2.79
##  6         6  1.67
##  7         7  1.92
##  8         8  2.60
##  9         9  2.47
## 10        10  3.12
## # ℹ 990 more rows
fr_conf_int <- fr_null_distribution %>%
  get_confidence_interval(level = 0.95, type = "percentile")


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

fr_null_distribution
## Response: tporgwk (factor)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  4.52
##  2         2 11.9 
##  3         3  7.50
##  4         4  4.95
##  5         5  2.79
##  6         6  1.67
##  7         7  1.92
##  8         8  2.60
##  9         9  2.47
## 10        10  3.12
## # ℹ 990 more rows

#T-statistic: A t-statistic of 371.071 is quite large, indicating a significant difference in types of organization they work/worked for between those with a BA and those without a BA. It suggests that the mean level of types of organization is different for the two groups.

#P-value: A p-value of 0.002 which is smaller than 0.05 means we can reject the null hypothesis with strong evidence.

#Visualization: Visualizes the null distribution alongside the observed test statistic (the red line), indicating here clear evidence, under assumptions of frequentist hypothesis testing, to reject the null.

#Appropriate test: According to the lecture slides, in this case independent variable is categorical variable with two categories, dependent variable is categorical variable with three or more categories, that would give us chi-square test of independence as the most appropriate test.

#Takeaways:I had trouble picking the right variables initially. I chose an independent numeric variable and a dependent categorical variable with three or more categories, but it didn’t work out. So, I had to change my variables to get better results. At the same time, I made sure my new choices would help form a solid research question.