# List of packages needed
packages <- c("tidyverse", "infer", "fst") # Add any packages 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
## [[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.

# Create variable educ_level and recode brncntr
switzerland_data <- ess %>%
  filter(cntry == "CH") 
  
swiss_data <- switzerland_data %>%
  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"
    ),
    brncntr = case_when(
      brncntr == 1 ~ "Yes",
      brncntr == 2 ~ "No",
      brncntr %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(brncntr)
    )
  )
# Generating Expected Proportions and Frequencies
tab_dat <- swiss_data
mytab <- table(tab_dat$educ_level, tab_dat$brncntr)
rsums <- rowSums(mytab)
csums <- colSums(mytab)
N <- sum(mytab)

ptab <- tcrossprod(rsums/N, csums/N) # Conditional proportions
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
print(ptab)
##            [,1]      [,2]
## [1,] 0.05206627 0.1757893
## [2,] 0.17643931 0.5957051
ftab <- N * ptab # Expected frequencies
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##           [,1]      [,2]
## [1,]  881.1175  2974.882
## [2,] 2985.8825 10081.118
# Critical Value for Independence
alpha <- 0.05 
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841
# 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
# P Value
p_val <- pchisq(test_stat, df = 1, lower.tail = F)
cat("p-value:", round(p_val, 4), "\n")
## p-value: 0

We can interpret the critical value of 3.841 in that if the X-squared test statistic that we calculate is greater than this value, then we have sufficient evidence to reject the null hypothesis at the 0.05 significance level. That would indicate a statistically significant association between being born in the country and one’s education level in the dataset.

Given that our X-squared test-statistic of 65.1218 is significantly larger than the critical value of 3.841, we have sufficient evidence to reject the null hypothesis that there is no difference in one’s education level based on if one was born in the country. Therefore, there is a statistically significant association between whether or not one was born in the country and one’s education levels. The difference between the observed data and what we’d expected under the assumption of independence is statistically significant.

Because the p-value is very small (0), we have sufficient evidence to reject the null hypothesis that the variables “brncntr” and “educ_level” are independent from each other. This means that there is a statistically significant relationship between one’s education level and whether or not they were born in this country, which aligns with the conclusion we can assume from comparing the X-squared test statistic and the critical value.

Overall given the p-value and the test-statistic calculated, we can say we have sufficient evidence to assume that there is a relationship between whether or not one is born in the country (Switzerland), and one’s education level.

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

# Recoding Netherlands Data
netherlands_data <- ess %>% 
  filter(cntry == "NL")

nl_data <- netherlands_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_),
         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)
         )
  )
set.seed(613)

# Calculate test-statistic
test_stat <- nl_data %>%
  specify(explanatory = geo, 
          response = gincdif) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq")
test_stat$stat
## X-squared 
##  8.176048
# Simulate the null hypothesis
null_distribution <- nl_data %>%
  specify(explanatory = geo,
          response = gincdif) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "chisq")

# Calculate p-value
p_val <- null_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1    0.19
# Visualization
null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided")

null_distribution
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  9.31
##  2         2  2.93
##  3         3  4.82
##  4         4  3.92
##  5         5  2.00
##  6         6  6.49
##  7         7  1.46
##  8         8  4.25
##  9         9  3.82
## 10        10  3.04
## # ℹ 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)

Because the p-value of 0.148 is greater than the significance level of 0.05, we fail to reject the null hypothesis in which the variables, geographic location and whether or not the government should reduce income differences is independent. Furthermore, as we can see that the test-statistic (red bar), falls within the 95% confidence interval, we have sufficient evidence to suggest no relationship between one’s place of location and whether or not one thinks that the government should reduce differences in income levels.

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.

A research question that I’m interested in is looking at the how one’s place of location how much one values having a good time in life. As Sweden is known for being a happy country, and being happy is associated with having a good time, I want to see how this varies based on one’s place of location. The explanatory variable of interest is domicil, while the outcome variable is ipgdtim.

# Filtering and recoding data
sweden_data <- ess %>% 
  filter(cntry == "SE")

sweden_df <- sweden_data %>% 
  mutate(ipgdtim = case_when(
         ipgdtim == 1 ~ "Very much like me",
         ipgdtim == 2 ~ "Like me",
         ipgdtim == 3 ~ "Somewhat like me",
         ipgdtim == 4 ~ "A little like me",
         ipgdtim == 5 ~ "Not like me",
         ipgdtim == 6 ~ "Not like me at all",
         ipgdtim %in% c(7, 8, 9) ~ NA_character_,
         TRUE ~ as.character(ipgdtim)),
    
         geo = recode(as.character(domicil), 
                      '1' = "Urban", 
                      '2' = "Urban",
                      '3' = "Rural", 
                      '4' = "Rural", 
                      '5' = "Rural",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_)
    )
# Calculate test-statistic
test_stat <- sweden_df %>%
  specify(explanatory = geo, 
          response = ipgdtim) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq")
test_stat$stat
## X-squared 
##  56.15435
# Simulate the null hypothesis
null_distribution <- sweden_df %>%
  specify(explanatory = geo,
          response = ipgdtim) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "chisq")

# Calculate p-value
p_val <- null_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0
# Visualization
null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "two-sided")

null_distribution
## Response: ipgdtim (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1  9.10 
##  2         2 16.2  
##  3         3  3.17 
##  4         4  2.43 
##  5         5  1.25 
##  6         6  6.74 
##  7         7  2.64 
##  8         8  1.96 
##  9         9  6.17 
## 10        10  0.987
## # ℹ 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)

From this data, we can see that based on the p-value of 0, we have sufficient evidence to reject the null hypothesis that the variables ipgdtim and domicil are independent from each other. This suggests that there is a significant association between geographical location and importance of having a good time in Sweden. Furthermore, if we look at the null hypothesis visualization, the test-statistic, depicted by the red line, is way outside the confidence interval range, indicating that there sufficient evidence to suggest a relationship between geographical location and the importance of having a good time.