SET UP
# List of packages
packages <- c("tidyverse", "infer", "fst") # 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"
ess <- read_fst("All-ESS-Data.fst")
TASK 1
# data cleaning and selection fot brncntr and educ_level
suisse_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)
),
educ_level = case_when(
essround < 5 & edulvla == 5 ~ "BA",
essround >= 5 & edulvlb > 600 ~ "BA",
TRUE ~ "No BA"
)
)
#Table of Expected Proportions
tab_dat <- suisse_data
mytab1 <- table(tab_dat$brncntr, tab_dat$educ_level)
rsums1 <- rowSums(mytab1)
csums1 <- colSums(mytab1)
N <- sum(mytab1)
ptab1 <- tcrossprod(rsums1/N, csums1/N)
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
print(ptab1)
## [,1] [,2]
## [1,] 0.05213379 0.1763718
## [2,] 0.17601725 0.5954772
# Table of expected frequencies
ftab1 <- N * ptab1
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab1)
## [,1] [,2]
## [1,] 882.2601 2984.74
## [2,] 2978.7399 10077.26
# 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 chi-squared test exceeds 3.841, we reject the null hypothesis, meaning that there is a definite relationship between the two variables of interest. the chi-squared test denotes how much our observed data deviates from what we would expect if our variables of interest were independent.
# Pearson's chi-squared statistic:
test_stat1 <- sum((mytab1 - ftab1)^2 / ftab1)
cat("Pearson's X^2:", round(test_stat1, 4), "\n")
## Pearson's X^2: 65.6673
# p-value:
p_val1 <- pchisq(test_stat1, df = 1, lower.tail = F)
cat("p-value:", round(p_val1, 4), "\n")
## p-value: 0
# Using chisq.test for validation:
cat("Chi-squared test result:\n")
## Chi-squared test result:
print(chisq.test(mytab1, correct = F))
##
## Pearson's Chi-squared test
##
## data: mytab1
## X-squared = 65.667, df = 1, p-value = 5.339e-16
# INTERPRETATION: Compared to the critical value, the chi-squared is much higher, indicating statistical significance. From this, we can come to the conclusion that there is a statistically significant correlation between being born in one's country and one's education level. This also indicates there is variation amongst one's education level and being born in the country the ESS is taking place in.
# The extremely low p-value (close to 0), also tells us to reject the null hypothesis - otherwise, that there is a stastically significant relationship between the two variables. Furthermore, the chi-squared being a high value also inforces this interpretation.
TASK 2
# DATA CLEANING
datanl <- 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",
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_ ),
)
test_stat <- datanl %>%
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
null_nl <- datanl %>%
specify(explanatory = geo,
response = gincdif) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "chisq")
## Warning: Removed 198 rows containing missing values.
pvalnl <- null_nl %>% # replace name here if you assigned something other than null_distribution above
get_pvalue(obs_stat = test_stat, direction = "greater") # would only replace test_stat if assigned another name in Step 1
pvalnl
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0.002
null_nl %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "greater")

null_nl
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 13.6
## 2 2 7.19
## 3 3 7.02
## 4 4 12.1
## 5 5 7.43
## 6 6 4.88
## 7 7 3.27
## 8 8 7.85
## 9 9 4.79
## 10 10 11.5
## # ℹ 990 more rows
nlconf <- null_nl %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_nl %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided") +
shade_confidence_interval(endpoints = nlconf)
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.

null_nl
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 13.6
## 2 2 7.19
## 3 3 7.02
## 4 4 12.1
## 5 5 7.43
## 6 6 4.88
## 7 7 3.27
## 8 8 7.85
## 9 9 4.79
## 10 10 11.5
## # ℹ 990 more rows
#INTERPRETATION:
# given the lecture slide, and the variable types, the most appropriate test would be the chi-squared test for independence.
# the p-value being close to 0 means that we can reject the null hypothesis, as we have statistically significant data pointing towards the fact that the two variables are related.
# furthermore, the x-value being 24.815, larger than the critical interval, indicates a statistically significant difference between the two variables of interesting, indicating the mean belief government should reduce differences in income is different for the groups living in urban areas than those living in rural areas.
TASK 3
# Research Question: How does the state of the economy in Bulgaria affect the levels of happiness?
# We chose Bulgaria as the country of interest as it has taken part in every ESS cycle, so we could research over time.
# happy - how happy are you https://ess-search.nsd.no/en/variable/a5c95af9-6037-4e52-9156-2ceac708eb3f
# hinctnta - Household's total net income, all sources https://ess-search.nsd.no/variable/d9e71465-7924-46f1-84eb-5fabf82be9a6
# data cleaning
bulgariadata <- ess %>%
filter(cntry == "BG") %>%
mutate(
hap = recode(as.character(domicil),
'1' = "Extremely unhappy",
'2' = "2",
'3' = "3",
'4' = "4",
'5' = "5",
'6' = "6",
'7' = "7",
'8' = "8",
'9' = "9",
'10' = "Extremely happy",
'77' = NA_character_,
'88' = NA_character_,
'99' = NA_character_),
inc = recode(as.character(hinctnta),
'1' = "1st decile",
'2' = "2nd decile",
'3' = "3rd decile",
'4' = "4th decile",
'5' = "5th decile",
'6' = "6th decile",
'7' = "7th decile",
'8' = "8th decile",
'9' = "9th decile",
'10' = "10th decile",
'77' = NA_character_,
'88' = NA_character_,
'99' = NA_character_)
)
# hypothesis testing
inchappy <- bulgariadata %>%
specify(explanatory = inc, # change variable name for explanatory variable
response = hap) %>%
hypothesize(null = "independence") %>%
calculate(stat = "chisq") # replace in between quotation marks appropriate test statistic
## Warning: Removed 5105 rows containing missing values.
print(inchappy$stat)
## X-squared
## 722.6612
# the x-squared value being this high indicates an extreme statistical significance between levels of happiness and the household's total net income. i am wondering though if it is this high because of how many variables there are at play.
bg_null <- bulgariadata %>%
specify(explanatory = inc,
response = hap) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "chisq")
## Warning: Removed 5105 rows containing missing values.
bg_pval <- bg_null %>% # replace name here if you assigned something other than null_distribution above
get_pvalue(obs_stat = inchappy, direction = "greater") # would only replace test_stat if assigned another name in Step 1
## 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.
bg_pval
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0
# this p-value indicates that the values are related, and we reject the null hypothesis.
bg_null %>%
visualize() +
shade_p_value(obs_stat = inchappy, direction = "greater")
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

bg_null
## Response: hap (factor)
## Explanatory: inc (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 37.5
## 2 2 54.9
## 3 3 32.7
## 4 4 41.8
## 5 5 41.3
## 6 6 33.2
## 7 7 50.2
## 8 8 49.7
## 9 9 42.2
## 10 10 49.7
## # ℹ 990 more rows
bg_conf <- bg_null %>%
get_confidence_interval(level = 0.95, type = "percentile")
bg_null %>%
visualize() +
shade_p_value(obs_stat = inchappy, direction = "greater") +
shade_confidence_interval(endpoints = bg_conf)
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

#the observed test statistic falls outside the null distribution, again indicating we ought to reject the null hypothesis. with all these tests: the chi squared value, the p-value, and the simulation null testing with the confidence interval, we can conlcude that these two variables are related, and thus, we reject the null hypothesis.