### Setting Working Directory
setwd("~/Desktop/SOC202")
### Loading Packages and ESS
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer",
"fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer")
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
## Loading required package: viridisLite
##
##
## Attaching package: 'flextable'
##
##
## The following object is masked from 'package:purrr':
##
## compose
## [[1]]
## [1] "lubridate" "forcats" "stringr" "dplyr" "purrr" "readr"
## [7] "tidyr" "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [13] "grDevices" "utils" "datasets" "methods" "base"
##
## [[2]]
## [1] "modelsummary" "lubridate" "forcats" "stringr" "dplyr"
## [6] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [11] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [16] "datasets" "methods" "base"
##
## [[3]]
## [1] "modelsummary" "lubridate" "forcats" "stringr" "dplyr"
## [6] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [11] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [16] "datasets" "methods" "base"
##
## [[4]]
## [1] "RColorBrewer" "modelsummary" "lubridate" "forcats" "stringr"
## [6] "dplyr" "purrr" "readr" "tidyr" "tibble"
## [11] "ggplot2" "tidyverse" "stats" "graphics" "grDevices"
## [16] "utils" "datasets" "methods" "base"
##
## [[5]]
## [1] "fst" "RColorBrewer" "modelsummary" "lubridate" "forcats"
## [6] "stringr" "dplyr" "purrr" "readr" "tidyr"
## [11] "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [16] "grDevices" "utils" "datasets" "methods" "base"
##
## [[6]]
## [1] "viridis" "viridisLite" "fst" "RColorBrewer" "modelsummary"
## [6] "lubridate" "forcats" "stringr" "dplyr" "purrr"
## [11] "readr" "tidyr" "tibble" "ggplot2" "tidyverse"
## [16] "stats" "graphics" "grDevices" "utils" "datasets"
## [21] "methods" "base"
##
## [[7]]
## [1] "knitr" "viridis" "viridisLite" "fst" "RColorBrewer"
## [6] "modelsummary" "lubridate" "forcats" "stringr" "dplyr"
## [11] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [16] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [21] "datasets" "methods" "base"
##
## [[8]]
## [1] "rmarkdown" "knitr" "viridis" "viridisLite" "fst"
## [6] "RColorBrewer" "modelsummary" "lubridate" "forcats" "stringr"
## [11] "dplyr" "purrr" "readr" "tidyr" "tibble"
## [16] "ggplot2" "tidyverse" "stats" "graphics" "grDevices"
## [21] "utils" "datasets" "methods" "base"
##
## [[9]]
## [1] "ggridges" "rmarkdown" "knitr" "viridis" "viridisLite"
## [6] "fst" "RColorBrewer" "modelsummary" "lubridate" "forcats"
## [11] "stringr" "dplyr" "purrr" "readr" "tidyr"
## [16] "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [21] "grDevices" "utils" "datasets" "methods" "base"
##
## [[10]]
## [1] "ggridges" "rmarkdown" "knitr" "viridis" "viridisLite"
## [6] "fst" "RColorBrewer" "modelsummary" "lubridate" "forcats"
## [11] "stringr" "dplyr" "purrr" "readr" "tidyr"
## [16] "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [21] "grDevices" "utils" "datasets" "methods" "base"
##
## [[11]]
## [1] "questionr" "ggridges" "rmarkdown" "knitr" "viridis"
## [6] "viridisLite" "fst" "RColorBrewer" "modelsummary" "lubridate"
## [11] "forcats" "stringr" "dplyr" "purrr" "readr"
## [16] "tidyr" "tibble" "ggplot2" "tidyverse" "stats"
## [21] "graphics" "grDevices" "utils" "datasets" "methods"
## [26] "base"
##
## [[12]]
## [1] "flextable" "questionr" "ggridges" "rmarkdown" "knitr"
## [6] "viridis" "viridisLite" "fst" "RColorBrewer" "modelsummary"
## [11] "lubridate" "forcats" "stringr" "dplyr" "purrr"
## [16] "readr" "tidyr" "tibble" "ggplot2" "tidyverse"
## [21] "stats" "graphics" "grDevices" "utils" "datasets"
## [26] "methods" "base"
##
## [[13]]
## [1] "infer" "flextable" "questionr" "ggridges" "rmarkdown"
## [6] "knitr" "viridis" "viridisLite" "fst" "RColorBrewer"
## [11] "modelsummary" "lubridate" "forcats" "stringr" "dplyr"
## [16] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [21] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [26] "datasets" "methods" "base"
ess <- read_fst("All-ESS-Data.fst")
### TASK 1
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"
)
)
# Making sure data is really cleaned
unique(switzerland_data$brncntr)
## [1] "No" "Yes" NA
unique(switzerland_data$educ_level)
## [1] "BA" "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"
unique(switzerland_data$educ_level)
## [1] "BA" "No BA"
table(switzerland_data$brncntr)
##
## No Yes
## 3867 13056
table(switzerland_data$educ_level)
##
## BA No BA
## 3856 13067
mytab <- table(switzerland_data$brncntr, switzerland_data$educ_level)
rsums <- rowSums(mytab)
csums <- colSums(mytab)
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.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
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841
# Interpretation: If the critical value 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 being born in the country and education level.
# 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
# Interpretation: The difference between our observed data and what we'd expect under the assumption of independence is statistically significant. There is a statistically significant relationship between education level and being born in the country. Meaning, that the probability of being born in the country is not the same across different education levels.
# p-value:
p_val <- pchisq(test_stat, df = 1, lower.tail = F)
cat("p-value:", round(p_val, 4), "\n")
## p-value: 0
# Using chisq.test for validation:
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
# A p-value (7.041e-16 in scientific notation) extremely close to 0 means that the null hypothesis is rejected and the two variables are independent from each other.
# Main takeaway is that there is a high likelihood of a statistically significant relationship between the two variables in Switzerland.
### TASK 2
netherlands_data <- ess |>
filter(cntry == "NL") |>
mutate(
geo = recode(as.character(domicil),
'1' = "Urban",
'2' = "Peri-Urban",
'3' = "Rural",
'4' = "Rural",
'5' = "Rural",
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_),
gincdif = recode(as.character(gincdif),
'1' = "Agree strongly",
'2' = "Agree",
'3' = "Neither agree nor disagree",
'4' = "Disagree",
'5' = "Disagree strongly",
'6' = NA_character_,
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_)
)
table(netherlands_data$geo)
##
## Peri-Urban Rural Urban
## 1891 12681 3732
table(netherlands_data$gincdif)
##
## Agree Agree strongly
## 7894 2896
## Disagree Disagree strongly
## 3681 543
## Neither agree nor disagree
## 3142
# Calculating test statistic
test_stat <- netherlands_data |>
specify(explanatory = geo,
response = gincdif) |>
hypothesize(null = "independence") |>
calculate(stat = "Chisq")
## Warning: Removed 198 rows containing missing values.
print(test_stat$stat)
## X-squared
## 24.81544
# Simulating null distribution
null_distribution <- netherlands_data |>
specify(explanatory = geo,
response = gincdif) |>
hypothesize(null = "independence") |>
generate(reps = 1000, type = "permute") |>
calculate(stat = "Chisq")
## Warning: Removed 198 rows containing missing values.
# Calculating p-value
p_value <- null_distribution |>
get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_value
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0.004
# Visualizing test statistic and null distribution
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: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 5.13
## 2 2 12.6
## 3 3 7.45
## 4 4 12.4
## 5 5 9.68
## 6 6 14.4
## 7 7 8.14
## 8 8 5.16
## 9 9 9.20
## 10 10 14.4
## # ℹ 990 more rows
# Interpretation:
# When recoding the variable of domicil, I re-coded 2 as Peri-Urban as it was done in the Tutorial 4. Although, I ran through my code and what the results would be if 2 was recoded as Urban and this differs from the values I got.
# For the first step of calculating the test statistic, the chi-squared test statistic was chosen because it compares two categorical variables. The x-squared value of 24.82 is a lot larger than the critical value, suggesting a statistically significant relationship between the variables of area of residence (domicil) and the belief that the government should reduce differences in income levels (gincdif).
# For the third step of calculating the p-value, it was 0.006 which is less than 0.05, indicating statistical significance.
# For the fourth step of visualizing the null distribution, this further shows the statistical significance and the rejection of the null hypothesis under assumptions of frequentest hypothesis testing. As the observed statistic does not fall within the null distribution.
### TASK 3
# The research question my partner and I would like to consider is "How does gender relate to trust in the United Kingdom?" The main relationship would be between gender as the explanatory variable and trust as the outcome variable. In this case, we coded for the variable ppltrst (most people can be trusted or you can't be too careful).
UK_data <- ess |>
filter(cntry == "GB") |>
mutate(
gndr = case_when(
gndr == 1 ~ "Male",
gndr == 2 ~ "Female",
TRUE ~ NA_character_
),
ppltrst = ifelse(ppltrst %in% c(77, 88, 99), NA, ppltrst)
)
table(UK_data$ppltrst)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 802 508 1042 1946 2209 4639 2648 3831 2524 474 307
# Calculating test statistic
test_stat <- UK_data |>
specify(explanatory = gndr,
response = ppltrst) |>
hypothesize(null = "independence") |>
calculate(stat = "F")
## Warning: Removed 59 rows containing missing values.
print(test_stat$stat)
## [1] 13.71719
# Simulating null distribution
null_distribution <- UK_data |>
specify(explanatory = gndr,
response = ppltrst) |>
hypothesize(null = "independence") |>
generate(reps = 1000, type = "permute") |>
calculate(stat = "F")
## Warning: Removed 59 rows containing missing values.
# Calculating p-value
p_value <- null_distribution |>
get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_value
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0.002
# Visualizing test statistic and null distribution
null_distribution |>
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided")
## Warning: F usually corresponds to right-tailed tests. Proceed with caution.

null_distribution
## Response: ppltrst (numeric)
## Explanatory: gndr (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.367
## 2 2 0.360
## 3 3 0.726
## 4 4 0.671
## 5 5 2.25
## 6 6 0.713
## 7 7 0.0608
## 8 8 0.124
## 9 9 1.30
## 10 10 0.553
## # ℹ 990 more rows
# The calculated F-statistic value of 13.72 is greater than the critical value of 3.841, which means the null hypothesis should be rejected. And there exists a statistically significant relationship between the variables of gender (gndr) and trust in people (ppltrst).
# The p-value was 0, which is less than the significance level of 0.05, suggesting a statistically significant relationship between the two variables and providing strong evidence that the null hypothesis should be rejected.
# The observed statistic falls outside of the null distribution, which provides greater evidence of rejecting the null hypothesis under assumptions of frequentest hypothesis testing.
# My main takeaway is that there is likely an association between individuals gender and how much they think people can or cannot be trusted.