# List of packages
packages <- c("tidyverse", "infer", "fst", "questionr") # 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"
##
## [[4]]
## [1] "questionr" "fst" "infer" "lubridate" "forcats" "stringr"
## [7] "dplyr" "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [13] "tidyverse" "stats" "graphics" "grDevices" "utils" "datasets"
## [19] "methods" "base"
ess <- read_fst("All-ESS-Data.fst")
switzerland_data <- ess %>%
filter(cntry == "CH")
switzerland_data <- switzerland_data %>%
mutate(brncntr = recode(brncntr,
`1` = "Yes",
`2` = "No",
`7` = NA_character_,
`8` = NA_character_,
`9` = NA_character_))
table(switzerland_data$brncntr)
##
## No Yes
## 3867 13056
switzerland_data <- switzerland_data %>%
mutate(educ_level = case_when(
essround < 5 & edulvla == 5 ~ "BA",
essround >= 5 & edulvlb > 600 ~ "BA",
TRUE ~ "No BA"
))
table(switzerland_data$educ_level)
##
## BA No BA
## 3861 13064
switzerland_data <- switzerland_data %>% filter(!is.na(brncntr))
switzerland_data <- switzerland_data %>% filter(!is.na(educ_level))
unique(switzerland_data$brncntr)
## [1] "No" "Yes"
freq(switzerland_data$brncntr)
## n % val%
## No 3867 22.9 22.9
## Yes 13056 77.1 77.1
freq(switzerland_data$educ_level)
## n % val%
## BA 3861 22.8 22.8
## No BA 13062 77.2 77.2
tab_dat <- switzerland_data
mytab <- table(tab_dat$brncntr, 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:
print(ptab)
## [,1] [,2]
## [1,] 0.05213379 0.1763718
## [2,] 0.17601725 0.5954772
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
## [,1] [,2]
## [1,] 882.2601 2984.74
## [2,] 2978.7399 10077.26
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
The critical value of 3.84 represents the point beyond where the the null hypothesis would be rejected.
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 65.6673
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.667, df = 1, p-value = 5.339e-16
The p-value is 5.339e-16, which means the p-value is extremely close to zero. The very small p-value indicates that we can reject the null hypothesis that the variables brncntr and educ_level are independent of each other. This suggests that there is a significant association between the two variables. Additionally, the x-squared value/chi-squared statistic of 65.67 is much larger than the critical value of 3.84, also signifying the null hypothesis can be rejected. The difference between the observed data and what we could expect is statistically significant, meaning there is a significant association between being born in the country and a person’s education level in Switzerland. This means that education level is affected by being born in the country, since larger chi-squared statistics indicate variables are related.
netherlands_data <- ess %>%
filter(cntry == "NL")
netherlands_data <- netherlands_data %>%
mutate(domicil = recode(as.character(domicil),
'1' = "Urban",
'2' = "Urban",
'3' = "Rural",
'4' = "Rural",
'5' = "Rural",
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_))
netherlands_data <- netherlands_data %>%
mutate(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_))
netherlands_data <- netherlands_data %>% filter(!is.na(domicil))
netherlands_data <- netherlands_data %>% filter(!is.na(gincdif))
unique(netherlands_data$gincdif)
## [1] "Agree" "Disagree"
## [3] "Neither agree nor disagree" "Agree strongly"
## [5] "Disagree strongly"
unique(netherlands_data$domicil)
## [1] "Urban" "Rural"
#step 1
test_stat <- netherlands_data %>%
specify(explanatory = domicil, #explanatory
response = gincdif) %>% #outcome of interest
hypothesize(null = "independence") %>%
calculate(stat = "Chisq")
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") %>% # only line we are adding, use reps = 1000 as standard
calculate(stat = "Chisq")
#step 3
p_val <- null_distribution %>%
get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0.156
#step 4
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.
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.
In step 1, I used a Chi-square test of independence, and the X-squared
value was 8.18. The p-value in step 3 was 0.176, which is above the
statistically significant test p-value of 0.05. This means that we
cannot reject the null hypothesis. The simulation for the null
distribution shows the test statistic not being inside the critical
value area, and when we add the 95% confidence interval, we see clearly
the test statistic is within the interval. This means we fail to reject
the null hypothesis. The data suggests that the variables domicil and
gincdif are independent of each other, and there is no relationship
between living area (urban/rural) and opinion for if the government
should reduce differences in income levels.
The research question I want to consider for this task is if being born in the country (UK) has a relationship with the how interested people are in politics. Brncntr will be the explanatory variable, and polintr will be the outcome variable.
uk_data <- ess %>%
filter(cntry == "GB")
uk_data <- uk_data %>%
mutate(brncntr = recode(brncntr,
`1` = "Yes",
`2` = "No",
`7` = NA_character_,
`8` = NA_character_,
`9` = NA_character_))
uk_data <- uk_data %>%
mutate(polintr = recode(polintr,
`1` = "Very Interested",
`2` = "Quite Interested",
`3` = "Hardly Interested",
`4` = "Not at all Interested",
`7` = NA_character_,
`8` = NA_character_,
`9` = NA_character_))
uk_data <- uk_data %>% filter(!is.na(brncntr))
uk_data <- uk_data %>% filter(!is.na(polintr))
unique(uk_data$brncntr)
## [1] "Yes" "No"
unique(uk_data$polintr)
## [1] "Very Interested" "Hardly Interested" "Not at all Interested"
## [4] "Quite Interested"
test_stat <- uk_data %>%
specify(explanatory = brncntr,
response = polintr) %>%
hypothesize(null = "independence") %>%
calculate(stat = "Chisq")
print(test_stat$stat)
## X-squared
## 40.22857
null_distribution <- uk_data %>%
specify(explanatory = brncntr,
response = polintr) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "Chisq")
p_val <- 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.
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.
null_distribution
## Response: polintr (factor)
## Explanatory: brncntr (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.578
## 2 2 1.54
## 3 3 0.840
## 4 4 6.81
## 5 5 3.27
## 6 6 1.48
## 7 7 1.19
## 8 8 0.812
## 9 9 1.91
## 10 10 3.41
## # ℹ 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)
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.
After conducting the 4 steps, interpret all the output and discuss your
takeaways.
The first result of the Chi-square test gives a result of an X-squared value of 40.23. The p-value test I did next resulted in a value extremely close to zero, suggesting these results are significantly significant, since the value was lower than a p-value of 0.05. This suggests there is a relationship between the two variables, meaning we can reject the null hypothesis. The visualization of the distribution helps to show that the test statistic is outside of the critical value area. Adding the 95% confidence interval also helps to visualize that the test statistic does not align with the null hypothesis. This means that we reject the null hypothesis, and that there is a relationship between the variables brncntr and polintr. My takeaway from this is that being born in a country affects how interested you are in that country’s politics.