# 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
## [[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")
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"
))
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)
#Table of expected proportions
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
# 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 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
# 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
Our critical value for independence is 3.841, meaning that if our observed test statistic exceeds the value of 3.841, education level and whether or not you were born in the country would not be independent at the 0.05 significance level.
Our observed Pearson’s Chi-squared statistic was 65.1218, and our p-value was 0. With these values, we can interpret that we reject the null hypothesis as the observed Pearson Chi-squared value (65.1218) is greater than the critical value and the p-value (0) is less than 0.05. This would mean that there is a significant association between the variables’ education level (“edu_level”) and born in country (“brncntr”) - meaning the variables are likely, not independent.
netherlands_data <- ess %>%
filter(cntry == "NL") %>%
mutate(
domicil = case_when(
domicil == 1 ~ "Urban",
domicil == 2 ~ "Urban",
domicil == 3 ~ "Rural",
domicil == 4 ~ "Rural",
domicil == 5 ~ "Rural",
domicil %in% c(7, 8, 9) ~ NA_character_,
TRUE ~ as.character(domicil)
),
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)
))
tab_dat <- netherlands_data
mytab <- table(tab_dat$gndr, tab_dat$hincfel)
rsums <- rowSums(mytab)
csums <- colSums(mytab)
N <- sum(mytab)
# 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
# Step 1
test_stat <- netherlands_data %>%
specify(explanatory = domicil,
response = gincdif) %>%
hypothesize(null = "independence") %>%
calculate(stat = "chisq")
## Warning: Removed 198 rows containing missing values.
print(test_stat$stat)
## X-squared
## 8.176048
# Step 2
null_distribution <- netherlands_data %>%
specify(explanatory = domicil,
response = gincdif) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "chisq")
## Warning: Removed 198 rows containing missing values.
# Step 3
p_val <- null_distribution %>%
get_pvalue(obs_stat = test_stat, direction = "greater")
p_val
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0.09
# Step 4
null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "greater")
null_distribution
## Response: gincdif (factor)
## Explanatory: domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 2.05
## 2 2 10.8
## 3 3 3.25
## 4 4 3.03
## 5 5 3.30
## 6 6 2.62
## 7 7 3.54
## 8 8 3.40
## 9 9 2.34
## 10 10 6.34
## # ℹ 990 more rows
The test we chose given the table provided during the lecture was the Chi-square Test of Independence. We chose this test since our explanatory variable (“domicil”) is a categorical variable with 2 categories and our response variable (“gincdif”) is a categorical variable with more than 3 categories.
We observed a Chi-square statistic value of 8.176048 and a p-value of 0.085. Since the p-value is greater than the significance level of 0.05 we fail to reject the null hypothesis. This suggests that the categorical variables (“domicil” and “gincdif”) are not significantly related and are independent. The visualization supports this as there are clear cutoff points at the tail that stretch past the red line (the test statistic), and the observed statistic falls within the null distribution. However, since the red regions are not as extreme as our observed statistic this may mean that we may be able to reject the null hypothesis - we are unsure.
germany_data <- ess %>%
filter(cntry == "DE") %>%
mutate(
gndr = case_when(
gndr == 1 ~ "Male",
gndr == 2 ~ "Female",
gndr %in% c(9) ~ NA_character_,
TRUE ~ as.character(gndr)
),
hincfel = case_when(
hincfel == 1 ~ "Living comfortable on present income",
hincfel == 2 ~ "Coping on present income",
hincfel == 3 ~ "Difficult on present income",
hincfel == 4 ~ "Very difficult on present income",
hincfel %in% c(7, 8, 9) ~ NA_character_,
TRUE ~ as.character(hincfel)
))
tab_dat <- germany_data
mytab <- table(tab_dat$gndr, tab_dat$hincfel)
rsums <- rowSums(mytab)
csums <- colSums(mytab)
N <- sum(mytab)
# 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
# Step 1
gndr_stat <- germany_data %>%
specify(explanatory = gndr,
response = hincfel) %>%
hypothesize(null = "independence") %>%
calculate(stat = "chisq")
## Warning: Removed 918 rows containing missing values.
print(gndr_stat$stat)
## X-squared
## 30.05872
# Step 2
null_distribution <- germany_data %>%
specify(explanatory = gndr,
response = hincfel) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "chisq")
## Warning: Removed 918 rows containing missing values.
# Step 3
p_val <- null_distribution %>%
get_pvalue(obs_stat = gndr_stat, direction = "greater")
## 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
null_distribution %>%
visualize() +
shade_p_value(obs_stat = gndr_stat, direction = "greater")
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf
null_distribution
## Response: hincfel (factor)
## Explanatory: gndr (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 1.42
## 2 2 2.47
## 3 3 3.88
## 4 4 2.15
## 5 5 0.409
## 6 6 0.560
## 7 7 3.58
## 8 8 6.85
## 9 9 4.66
## 10 10 2.86
## # ℹ 990 more rows
conf_int <- null_distribution %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_distribution %>%
visualize() +
shade_p_value(obs_stat = gndr_stat, direction = "greater") +
shade_confidence_interval(endpoints = conf_int)
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf
Research Question: How does one’s gender affect their feelings about
household income nowadays, and is this a cause of the correlation
between gender and income?
After referring to the table, the test we decided to utilize was the Chi-square Test of Independence. We came to this conclusion as our independent variable (“gndr”) has two categories, and our dependent variable (“hincfel”) has 3 or more categories.
Our observed Chi-squared statistic is 30.05872 which is greater than the critical value of 3.841 and our p-value (0) is less than the significance level of 0.05, meaning that we reject the null hypothesis. With this, we can then see that there is a significant correlation between the variables “gndr” and “hincfel” and they are likely, not independent.
The visualization shows us that we reject the null hypothesis since we don’t see any shaded red regions in the null distribution and it is alongside the observed test statistic. This method of hypothesis testing tells us that a significance exists between our observations and variables. This then means the answer to our research question would explain that there is a significant correlation between one’s gender affecting the feelings they have about their current household income. With these interpretations, we can infer that in Germany, there is clear evidence of a relationship between gender and feelings about one’s income in connection to that.