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"
#Task 1
#Cleaning data and subsetting
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$educ_level)
## [1] "BA" "No BA"
table(switzerland_data$educ_level)
##
## BA No BA
## 3856 13067
#Generating the tables of expected proportions and frequencies
#Table of Expected Proportions
table_data <- switzerland_data
mytab <- table(table_data$brncntr, table_data$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
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841
#Generating 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
#Calculating P Value
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
#Due to the Chi-squared test statistic exceeding the critical value of 3.841, the null hypothesis at the 0.05 significance level is rejected. This means that there is a statistically significant association between being born in country and ones educational level in this data set.
#The extremely small p-value of 7.041e-16 (extremely close to 0) indicates that there is a significant association between the variables brncntr and educ_level (born in country and education level).
#The large chi-squared value of 65.12 tells us that the two variables mentioned above are dependent on each other, if the chi-squared value was closer to 0, these variables would be seen as independent.
#Task 2
netherlands_data <- ess %>%
filter(cntry == "NL") %>%
mutate(
domicil = case_when(
domicil == 1 ~ "Urban",
domicil == 2 ~ "Urban",
domicil == 3 ~ "Urban",
domicil == 4 ~ "Rural",
domicil == 5 ~ "Rural",
domicil %in% c(7, 8, 9) ~ NA_character_,
TRUE ~ as.character(domicil)
),
gincdif = case_when(
gincdif == 1 ~ "Strongly Agree",
gincdif == 2 ~ "Agree",
gincdif == 3 ~ "Neither Agree nor Disagree",
gincdif == 4 ~ "Disagree",
gincdif == 5 ~ "Strongly Disagree",
gincdif %in% c(7, 8, 9) ~ NA_character_,
TRUE ~ as.character(gincdif)
))
#Generating Pearson’s chi-squared statistic
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
## 19.87855
#The t-statistic value of 19.87855 indicates that there is a significant difference in the respondents’ opinion surrounding the prompt “Government should reduce differences in income levels” based on if they live in Urban or Rural domiciles. This also suggests that the mean level of agreement with the prompt “Government should reduce differences in income levels” is different in 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 198 rows containing missing values.
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: gincdif (factor)
## Explanatory: domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 8.24
## 2 2 2.54
## 3 3 7.02
## 4 4 10.0
## 5 5 10.5
## 6 6 0.906
## 7 7 2.66
## 8 8 2.65
## 9 9 4.49
## 10 10 2.85
## # ℹ 990 more rows
#visualized 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 = "two-sided") +
shade_confidence_interval(endpoints = conf_int)
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.
#Task 3
#A research question I would like to consider is "is there a relationship between being active in politics on the basis of being a good citizen and voting in national elections", I will explore this relationship in Germany.
germany_data <- ess %>%
filter(cntry == "DE") %>%
mutate(
impvote = recode(
as.character(impvote),
'0' = "Extremely unimportant",
'1' = "unimportant",
'2' = "unimportant",
'3' = "unimportant",
'4' = "unimportant",
'5' = "neither important nor unimportant",
'6' = "important",
'7' = "important",
'8' = "important",
'9' = "important",
'10' = "Extremely important",
'77' = NA_character_,
'88' = NA_character_,
'99' = NA_character_
)
)
table(germany_data$impvote)
##
## Extremely important Extremely unimportant
## 903 103
## important neither important nor unimportant
## 1318 299
## unimportant
## 269
germany_data <- germany_data %>%
mutate(
vote = recode(
as.character(vote),
'1' = 'Yes',
'2' = 'No',
'3' = 'No',
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_
)
)
table(germany_data$vote)
##
## No Yes
## 7618 26562
test_stat <- germany_data %>%
specify(
explanatory = vote,
response = impvote
) %>%
hypothesize(null = "independence") %>%
calculate(stat = "chisq")
## Warning: Removed 31539 rows containing missing values.
print(test_stat$stat)
## X-squared
## 436.0397
null_distribution <- germany_data %>%
specify(
explanatory = vote,
response = impvote
) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "chisq")
## Warning: Removed 31539 rows containing missing values.
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.
print(p_val)
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0
#Visualization
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: impvote (factor)
## Explanatory: vote (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 3.90
## 2 2 1.29
## 3 3 4.14
## 4 4 8.01
## 5 5 2.63
## 6 6 5.20
## 7 7 4.48
## 8 8 0.797
## 9 9 6.46
## 10 10 1.87
## # ℹ 990 more rows
print(null_distribution)
## Response: impvote (factor)
## Explanatory: vote (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 3.90
## 2 2 1.29
## 3 3 4.14
## 4 4 8.01
## 5 5 2.63
## 6 6 5.20
## 7 7 4.48
## 8 8 0.797
## 9 9 6.46
## 10 10 1.87
## # ℹ 990 more rows
#Visualization 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 = "two-sided") +
shade_confidence_interval(endpoints = conf_int)
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.
#There is strong evidence against the null hypothesis of independance, it can be seen that there is an association between the variables impvote (To be a good citizen: how important to vote in elections) and vote (Voted last national election). This question is worth further consideration as it can help look into the relationship between those who have and have not voted in the last national election in Germany and how important they believe it is to vote.
#The chi-squared test of 436.039 is very large, indicating a significant difference between how important is it to vote in elections to be a good citizen and those who did or didnt vote in the last national election. It further suggests that the mean level of people who believe it is important to vote in elections to be a good citizen is different for the two groups. The large chi-squared value also indicates that there is a strong assosication between the variables, if these 2 variables were independant, we’d expect a chi-square value closer to 0.
#Taking frequentist hypothesis testing into account, a p-value of 0 means there is strong evidence to reject the null hypothesis.