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")
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") %>%
# Recoding brncntr
mutate(
brncntr = case_when(
brncntr == 1 ~ "Yes", # Recode 1 to "Yes"
brncntr == 2 ~ "No", # Recode 2 to "No"
brncntr %in% c(7, 8, 9) ~ NA_character_,
TRUE ~ as.character(brncntr)
),
trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
# 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"
),
)
# using unique to identify
unique(switzerland_data$educ_level)
## [1] "BA" "No BA"
# does not return NA, but the following does
unique(switzerland_data$brncntr)
## [1] "No" "Yes" NA
# here's how to make sure it's really cleaned
switzerland_data <- switzerland_data %>% filter(!is.na(educ_level))
switzerland_data <- switzerland_data %>% filter(!is.na(brncntr))
# double-checking + quick distribution
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)
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
Interpreting the Critical Value: If the Chi-squared test statistic that you 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 feeling close to a party and education level in your dataset.
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("X^2:", round(test_stat, 4), "\n")
## 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 feeling close to a party and one’s educational level. This means that the probability of feeling close to a party 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(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.
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 for Netherlands
filter(cntry == "NL") %>%
# Recode domicil
mutate(
domicil = case_when(
domicil %in% c("a big city", "suburb or outskirts of big city", "town or small city") ~ "urban",
domicil %in% c("country village", "farm or home in countryside") ~ "rural",
TRUE ~ as.character(domicil)
)
) %>%
# Recode gincdif
mutate(
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)
)
)
chisq_test <- netherlands_data %>%
specify(explanatory = domicil,
response = gincdif) %>%
hypothesize(null = "independence") %>%
calculate(stat = "Chisq")
## Warning: Removed 173 rows containing missing values.
print(chisq_test$stat)
## X-squared
## 63.53213
Interpretation: The chi squared statistic measures the difference between the observed urban/rural and Government should reduce differences in income levels in units of standard error. The larger the magnitude of chi squared, the greater the evidence against the null hypothesis.
A chi squared statistic of 88.85496 is quite large, indicating a significant difference in trust in govenment between those live in urban and those live in rural. It suggests that the level of income is different for the two groups.
null_distribution <- netherlands_data %>%
specify(explanatory = domicil,
response = gincdif) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "chisq")
## Warning: Removed 173 rows containing missing values.
p_val <- null_distribution %>%
get_pvalue(obs_stat = test_stat, direction = "greater")
p_val
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0.002
Really, it’s essentially a p-value of 0.037, not 0 – but, still, under the assumptions of frequentist hypothesis testing, this means there is strong evidence to reject the null.
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 22.0
## 2 2 32.4
## 3 3 28.8
## 4 4 31.1
## 5 5 19.8
## 6 6 28.2
## 7 7 26.5
## 8 8 18.8
## 9 9 17.3
## 10 10 47.7
## # ℹ 990 more rows
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.
My research question: Does an individual’s level of responsibility for supervising other employees (jbspv) have a significant impact on their subjective general health (health)?
finland_data <- ess %>%
# Filter for Finland
filter(cntry == "FI") %>%
# Recoding jbspv
mutate(
jbspv = case_when(
jbspv == 1 ~ "Yes",
jbspv == 2 ~ "No",
jbspv %in% c(7, 8, 9) ~ NA_character_,
TRUE ~ as.character(jbspv)
),
# Recoding health
health = case_when(
health == 1 ~ "Very good",
health == 2 ~ "Good",
health == 3 ~ "Fair",
health == 4 ~ "Bad",
health == 5 ~ "Very bad",
health %in% c(7, 8, 9) ~ NA_character_,
TRUE ~ as.character(health)
),
# Recoding trstplt
trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt)
)
test_stat <- finland_data %>%
specify(explanatory = jbspv,
response = health) %>%
hypothesize(null = "independence") %>%
calculate(stat = "chisq")
## Warning: Removed 39 rows containing missing values.
print(test_stat$stat)
## X-squared
## 47.13497
Interpretation: The chi squared statistic measures the difference between subjective general health and responsibility for supervising other employees in individuals of standard error. The larger the magnitude of chi squared, the greater the evidence against the null hypothesis.
A chi squared statistic of 47.13497 is quite large, indicating a significant difference in subjective general health between those with responsibility for supervising other employees in individuals and those without. It suggests that the mean individual level in subjective general health is different for the two groups.
null_distribution <- finland_data %>%
specify(explanatory = jbspv,
response = health) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "chisq")
## Warning: Removed 39 rows containing missing values.
p_val <- null_distribution %>%
get_pvalue(obs_stat = test_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
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.
null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "greater")
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf
null_distribution
## Response: health (factor)
## Explanatory: jbspv (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 9.19
## 2 2 3.99
## 3 3 3.74
## 4 4 7.55
## 5 5 5.60
## 6 6 4.19
## 7 7 7.84
## 8 8 6.19
## 9 9 4.85
## 10 10 5.08
## # ℹ 990 more rows
Visualizes the null distribution alongside the observsed test statistic (the red line), indicating here clear evidence, under assumptions of frequentist hypothesis testing, to reject the null. If the observed statistic would fall within the null distribution, you would see shaded red regions of the null distribution that are as (or more) extreme than our observed statistic.
We can also visualize with confidence intervals.
conf_int <- null_distribution %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "greater") +
shade_confidence_interval(endpoints = conf_int)
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf
null_distribution
## Response: health (factor)
## Explanatory: jbspv (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 9.19
## 2 2 3.99
## 3 3 3.74
## 4 4 7.55
## 5 5 5.60
## 6 6 4.19
## 7 7 7.84
## 8 8 6.19
## 9 9 4.85
## 10 10 5.08
## # ℹ 990 more rows
Reference from Tutorial_6