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

# Install packages if they aren't installed already
new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)

# Load the 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
## Warning: package 'infer' was built under R version 4.3.2
## [[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

The Task: 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 for Switzerland
  filter(cntry == "CH") %>%
  
  mutate(
    # Recoding education for rounds 1-4
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    
    # Re-coding education for rounds 5 and later
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    
    # Create educ_level column
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "No BA"
    ),
    
    born_in_country = recode(brncntr,
                                  `1` = "Yes",
                                  `2` = "No",
                                  `7` = NA_character_,
                                  `8` = NA_character_,
                                  `9` = NA_character_)
  )
# using unique to identify
unique(switzerland_data$educ_level)
## [1] "BA"    "No BA"
unique(switzerland_data$born_in_country)
## [1] "No"  "Yes" NA
switzerland_data <- switzerland_data %>% filter(!is.na(educ_level))
switzerland_data <- switzerland_data %>% filter(!is.na(born_in_country))
table(switzerland_data$educ_level)
## 
##    BA No BA 
##  3856 13067
table(switzerland_data$born_in_country)
## 
##    No   Yes 
##  3867 13056

Calculating and interpreting critical value for independence

## Not necessary, but always good to rename when doing operations so you can backtrack to clean dataset
tab_dat <- switzerland_data

# Create a crosstable and save it into the object mytab
mytab <- table(tab_dat$born_in_country, tab_dat$educ_level)

# Calculate row-wise sums of counts in table 
rsums <- rowSums(mytab)

# Calculate column-wise sums of counts in table
csums <- colSums(mytab)

# Get the total count of the table (N)
N <- sum(mytab)

# Generate table of expected proportions
ptab <- tcrossprod(rsums/N, csums/N)
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
## Table of Expected Proportions:
print(ptab)
##            [,1]      [,2]
## [1,] 0.05206627 0.1764393
## [2,] 0.17578931 0.5957051
# Table of expected frequencies
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
## Table of Expected Frequencies:
print(ftab)
##           [,1]      [,2]
## [1,]  881.1175  2985.882
## [2,] 2974.8825 10081.118
# Critical Value for Independence:
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

Interpreting the Critical Value: If the Chi-squared test statistic that I 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 being born in Switzerland and education level in my dataset.

Calculating and interpreting Pearson’s chi-squared statistic

# Pearson's chi-squared statistic:
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: We previously calculated a critical value of 3.841. Our observed X-squared value is much larger than this critical value.

Calculating the p-value

# p-value:
p_val <- pchisq(test_stat, df = 1, lower.tail = F)
cat("p-value:", round(p_val, 4), "\n")
## p-value: 0
# Using chisq.test for validation:
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

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 the two variables in mytab.

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.

Task 2

The Task: 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).

See variable info here:

https://ess-search.nsd.no/en/variable/1ad9f42e-0c02-4b13-9a67-ee83d82ac576

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 = case_when(
           gincdif == '1' ~ "Agree strongly",
           gincdif == '2' ~ "Agree",
           gincdif == '3' ~ "Neither agree nor disagree",
           gincdif == '4' ~ "Disagree",
           gincdif == '5' ~ "Disagree strongly",
           gincdif %in% c(7, 8, 9) ~ NA_character_,
           TRUE ~ as.character(gincdif)
         )
)
netherlands_data <- netherlands_data %>% filter(!is.na(geo))
netherlands_data <- netherlands_data %>% filter(!is.na(gincdif))
test_stat <- netherlands_data %>%
  specify(explanatory = geo, 
          response = gincdif) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq")
print(test_stat$stat)
## X-squared 
##  24.81544

Interpretation: The Chi-square test of independence tests the association between two categorical variables. It is the best test statistic to use according to the lecture when the explanatory and response variables are each one category variable with more than two categories. The Chi-square test of independence determines if the observed frequencies differ from expected frequencies. However, the Chi-square test of independence does not indicate the strength or direction of the association. The larger the number of chi-squared statistic, the greater the evidence against the null hypothesis.

null_distribution <- netherlands_data %>%
  specify(explanatory = geo,
          response = gincdif) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "chisq")
p_val <- 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

p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.004

Interpretation: Really, it’s essentially a p-value of 0, not 0 – but, still, under the assumptions of frequentist hypothesis testing, this means there is strong evidence to reject the null.

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: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  5.59
##  2         2  6.26
##  3         3  4.60
##  4         4 10.1 
##  5         5  4.20
##  6         6 19.1 
##  7         7  7.13
##  8         8  6.10
##  9         9  6.27
## 10        10  3.20
## # ℹ 990 more rows

Interpretation: The the observed test statistic (the red line) falls outside the confidence interval of the simulated null distribution. We can reject the null hypothesis and assume there to be a relationship between domicil and gincdif. However, the direction of the association is unknown.

Task 3

The Task: 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 of interest: how one’s location of residence, that is, living in an urban or rural area (explanatory variable), relate to their views of how many immigrants should be allowed from poorer countries outside of Europe (outcome variable). My country of interest is France.

france_data <- ess %>%
  filter(cntry == "FR") %>% 
  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_), 
    impcntr = recode(as.character(impcntr), 
                      '1' = "Allow many to come and live here", 
                      '2' = "Allow some",
                      '3' = "Allow a few", 
                      '4' = "Allow none", 
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_)
    )
france_data <- france_data %>% filter(!is.na(geo))
france_data <- france_data %>% filter(!is.na(impcntr))
test_stat <- france_data %>%
  specify(explanatory = geo, # change variable name for explanatory variable
          response = impcntr) %>% # change variable name for outcome of interest
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq") # replace in between quotation marks appropriate test statistic
print(test_stat$stat)
## X-squared 
##  244.3959
null_distribution <- france_data %>%
  specify(explanatory = geo,
          response = impcntr) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
  calculate(stat = "chisq")
null_distribution
## Response: impcntr (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  5.51
##  2         2  3.12
##  3         3  1.40
##  4         4  4.26
##  5         5  2.72
##  6         6  3.32
##  7         7  4.17
##  8         8  3.38
##  9         9  3.21
## 10        10 14.2 
## # ℹ 990 more rows
p_val <- 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
## 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.

Interpretation:

I used the Chi-square test of independence to address my research question. The Chi-square test of independence tests the association between two categorical variables. It is the best test statistic to use according to the lecture when the explanatory and response variables are each one category variable with more than two categories.

The reported p-value is displayed as 0, although it cannot truly be zero, as it pertains to probability and, by definition, cannot reach absolute zero. The apparent value of 0 in the output of my code might arise from the R program not providing additional decimal place precision. Nonetheless, the p-value is extremely close to zero. According to the assumptions of frequentist hypothesis testing, this proximity to zero indicates strong evidence to reject the null hypothesis.

The the observed test statistic (the red line) falls outside the confidence interval of the simulated null distribution. We can reject the null hypothesis and assume there to be a relationship between one’s location of residence (urban or rural) and their views of how immigrants to be allowed from poorer countries outside of Europe. However, the direction of the association is unknown.