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")
swiss_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)
),
trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
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"
),
gndr = case_when(
gndr == 1 ~ "Male",
gndr == 2 ~ "Female",
gndr == 9 ~ NA_character_,
TRUE ~ as.character(gndr)
)
)
unique(swiss_data$gndr)
## [1] "Female" "Male" NA
unique(swiss_data$brncntr)
## [1] "No" "Yes" NA
swiss_data <- swiss_data %>% filter(!is.na(brncntr))
swiss_data <- swiss_data %>% filter(!is.na(trstplt))
swiss_data <- swiss_data %>% filter(!is.na(educ_level))
unique(swiss_data$brncntr)
## [1] "No" "Yes"
tab_dat <- swiss_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.05018556 0.1673515
## [2,] 0.18051337 0.6019496
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
## [,1] [,2]
## [1,] 823.5951 2746.405
## [2,] 2962.4049 9878.595
alpha <- 0.05
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 75.4503
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 = 75.45, df = 1, p-value < 2.2e-16
The x-squared value, 75.45, is much bigger than the critical value, 3.841, which shows that the education level and whether born in Switzerland is statistically significant. As the p-value is extremely close to 0, it is possible to infer that the two variables, education level and brncntr, are associated.
netherlands_data <- ess %>%
filter(cntry == "NL") %>%
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_),
gincdif = recode(as.character(gincdif),
'1' = "Agree",
'2' = "Agree",
'3' = "Agree",
'4' = "Disagree",
'5' = "Disagree",
'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"
unique(netherlands_data$domicil)
## [1] "Urban" "Rural"
test_stat <- netherlands_data %>%
specify(explanatory = domicil,
response = gincdif,
success = "Agree") %>%
hypothesize(null = "independence") %>%
calculate(stat = "z")
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "Rural" - "Urban", or divided in the order "Rural" / "Urban" for
## ratio-based statistics. To specify this order yourself, supply `order =
## c("Rural", "Urban")` to the calculate() function.
print(test_stat$stat)
## [1] -2.328809
null_distribution <- netherlands_data %>%
specify(explanatory = domicil,
response = gincdif,
success = "Agree") %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "z")
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "Rural" - "Urban", or divided in the order "Rural" / "Urban" for
## ratio-based statistics. To specify this order yourself, supply `order =
## c("Rural", "Urban")` to the calculate() function.
p_val <- null_distribution %>%
get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0.016
null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided")
null_distribution
## Response: gincdif (factor)
## Explanatory: domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 1
## stat
## <dbl>
## 1 2.47
## 2 0.187
## 3 -0.537
## 4 1.45
## 5 -0.690
## 6 -1.26
## 7 -1.57
## 8 -0.194
## 9 -0.537
## 10 -1.34
## # ℹ 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)
null_distribution
## Response: gincdif (factor)
## Explanatory: domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 1
## stat
## <dbl>
## 1 2.47
## 2 0.187
## 3 -0.537
## 4 1.45
## 5 -0.690
## 6 -1.26
## 7 -1.57
## 8 -0.194
## 9 -0.537
## 10 -1.34
## # ℹ 990 more rows
Through the null distribution, it is possible to infer that the domicil variable is normally distributed, while the response variable gincdif is extremely skewed on the left, showing that fewer people agreed as people live in urban areas. Besides, the p-value and calculation suggest that the association between variable domicil and gincdif is low.
How is the education level associated with the trust in politicians?
spain_data <- ess %>%
filter(cntry == "ES") %>%
mutate(
trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
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"
)
)
spain_data <- spain_data %>% filter(!is.na(trstplt))
spain_data <- spain_data %>% filter(!is.na(educ_level))
test_stat <- spain_data %>%
specify(explanatory = educ_level,
response = trstplt) %>%
hypothesize(null = "independence") %>%
calculate(stat = "t")
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "BA" - "No BA", or divided in the order "BA" / "No BA" for ratio-based
## statistics. To specify this order yourself, supply `order = c("BA", "No BA")`
## to the calculate() function.
print(test_stat$stat)
## t
## 3.597886
n_dist <- spain_data %>%
specify(explanatory = educ_level,
response = trstplt) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "t")
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "BA" - "No BA", or divided in the order "BA" / "No BA" for ratio-based
## statistics. To specify this order yourself, supply `order = c("BA", "No BA")`
## to the calculate() function.
p_val <- n_dist %>%
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
n_dist %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided")
n_dist
## Response: trstplt (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.582
## 2 2 0.876
## 3 3 -1.58
## 4 4 -0.825
## 5 5 -0.00913
## 6 6 -2.03
## 7 7 -1.17
## 8 8 -1.05
## 9 9 -0.837
## 10 10 -0.279
## # ℹ 990 more rows
conf_int <- n_dist %>%
get_confidence_interval(level = 0.95, type = "percentile")
n_dist %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided") +
shade_confidence_interval(endpoints = conf_int)
n_dist
## Response: trstplt (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.582
## 2 2 0.876
## 3 3 -1.58
## 4 4 -0.825
## 5 5 -0.00913
## 6 6 -2.03
## 7 7 -1.17
## 8 8 -1.05
## 9 9 -0.837
## 10 10 -0.279
## # ℹ 990 more rows
As the result is far from the confidence interval, it is possible to infer that the result happened by chance. In addition, we can possibly conclude that there is extremely low or no association between the education level and trust in politicians in Spain.