packages <- c("tidyverse", "infer", "fst") # add any you need here

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")

Task 1

Set up the calculations for an exploration of educ_level (as BA, No BA) and brncntr (recoded as yes/no *shown in tutorial 4) for Switzerland. Using the steps outlined in the tutorial, first generate the tables of expected proportions and frequencies. Determine and interpret the critical value for independence. Finally, determine and interpret both the Pearson’s chi-squared statistic and the p-value. Discuss main takeaways.

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"
    )
  )
    
tab_dat <- switzerland_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.05206627 0.1764393
## [2,] 0.17578931 0.5957051
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
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

Interepret the critical value: If the Chi-squared test statistic 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 born in the country and education level in the dataset.

Determine the chi-squared statistic and p-value:

test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 65.1218
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

Interpretation of chi-squared statistics and p-value: We previously calculated a critical value of 3.841. Our observed X-squared value (65.122) is much larger than this critical value.

The difference between our observed data and what we’d expect under the assumption of independence is statistically significant. Thus, there is a statistically significant association between being born in the country and one’s educational level. This means that the probability of being born in the country is not the same across different education levels.

p-value = 7.041e-16, extremely close to 0. It means that we reject the null hypothesis that the two variables are independent of each other.

Main takeway: We reject the null hypothesis that being born in the country and education level are independent of each other. There’s strong evidence to show that there’s a significant assocaition between these two variables for Switzerland.

Task 2

Using the infer package and following the 4 steps outlined in the tutorial and during the lecture, conduct and visualize the hypothesis testing for domicil (recoded as urban/rural – see tutorial 4) and gincdif (Government should reduce differences in income levels) for the country of Netherlands. For gincdif, you must recode for the five categories (i.e, cannot keep as numeric).

See variable info here:

https://ess-search.nsd.no/en/variable/1ad9f42e-0c02-4b13-9a67-ee83d82ac576

Make decision over appropriate test given table provided during lecture. After conducting the 4 steps, interpret all the output and discuss your takeaways.

netherlands_data <- ess %>%
  filter(cntry == "NL") %>%
  mutate(geo = 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 Strongly", 
                      '2' = "Agree", 
                      '3' = "Neither Agree nor Disagree", 
                      '4' = "Disagree", 
                      '5' = "Disagree Strongly",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_))

Step 1

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 
##  8.176048

Interpretation: A t-statistic of 8.2 is quite large, indicating quite a significant difference in believing that government should reduce differences in income levels between those living in urban area and those living in rural area. It suggests that the mean level of thinking that government should reduce differences in income levels is different for the two groups.

Step 2

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.

Step 3

p_val <- null_distribution %>% 
  get_pvalue(obs_stat = test_stat, direction = "greater") 

p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.094

Interpretation: p-value=0.09, that there was a 9 percent chance that we would have obtained our result if the null was true. It is greater than 0.05, we cannot reject the null hypothesis.

Step 4

null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "greater")

null_distribution
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 2.44 
##  2         2 0.602
##  3         3 1.00 
##  4         4 1.74 
##  5         5 3.17 
##  6         6 1.24 
##  7         7 8.44 
##  8         8 5.60 
##  9         9 1.73 
## 10        10 2.75 
## # ℹ 990 more rows

The red line is set based on the test statistic and we cannot reject the null as the standard cutoff points at the tails.

Takeway: Given that p>0.05 and the visualization above, we cannot reject the null hypothesis, and we cannot conclude that whether living in urban/rural area has an influence on politics (whther government should reduce difference in income levels) inference.

Task 3

First, talk about a research question you would like to consider, which identifies a main relationship between an explanatory variable and an outcome variable. Using the infer package and following the 4 steps outlined in the tutorial and during the lecture, conduct and visualize the hypothesis testing for your variables based on your research question. After conducting the 4 steps, interpret all the output and discuss your takeaways.

I would like to investigate whether residence type (living in rural/urban areas) will influence trust in other people (whether believing that most people can be trusted) in UK.

uk_data <- ess %>%
  filter(cntry == "GB") %>%
  mutate(geo = recode(as.character(domicil), 
                      '1' = "Urban", 
                      '2' = "Urban", 
                      '3' = "Rural", 
                      '4' = "Rural", 
                      '5' = "Rural",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_),
         ppltrst = ifelse(ppltrst %in% c(77, 88, 99), NA, ppltrst))

Step 1

test_stat_uk <- uk_data %>%
  specify(explanatory = geo, 
          response = ppltrst) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "F") 
## Warning: Removed 98 rows containing missing values.
print(test_stat_uk$stat)
## [1] 10.01227

Interpretation: A t-statistic of 10.0 is quite large, indicating quite a significant difference in trust in other people between those living in urban area and those living in rural area. It suggests that the mean level of trust in other people is different for the two groups.

Step 2

null_distribution_uk <- uk_data %>%
  specify(explanatory = geo,
          response = ppltrst) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "F")
## Warning: Removed 98 rows containing missing values.

Step 3

p_val_uk <- null_distribution_uk %>% 
  get_pvalue(obs_stat = test_stat_uk, direction = "greater") 

p_val_uk
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.003

Interpretation: p-value=0.003, which is quite close to 0. Also, given that it is smaller than 0.05, this means there is strong evidence to reject the null.

Step 4

null_distribution_uk %>%
  visualize() +
  shade_p_value(obs_stat = test_stat_uk, direction = "greater")

null_distribution_uk
## Response: ppltrst (numeric)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate     stat
##        <int>    <dbl>
##  1         1 1.01    
##  2         2 0.868   
##  3         3 0.0195  
##  4         4 0.0280  
##  5         5 0.000110
##  6         6 3.23    
##  7         7 0.134   
##  8         8 0.0353  
##  9         9 0.279   
## 10        10 1.04    
## # ℹ 990 more rows
conf_int <- null_distribution_uk %>%
  get_confidence_interval(level = 0.95, type = "percentile")


null_distribution_uk %>%
  visualize() +
  shade_p_value(obs_stat = test_stat_uk, direction = "greater") +
  shade_confidence_interval(endpoints = conf_int)

null_distribution_uk
## Response: ppltrst (numeric)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate     stat
##        <int>    <dbl>
##  1         1 1.01    
##  2         2 0.868   
##  3         3 0.0195  
##  4         4 0.0280  
##  5         5 0.000110
##  6         6 3.23    
##  7         7 0.134   
##  8         8 0.0353  
##  9         9 0.279   
## 10        10 1.04    
## # ℹ 990 more rows

Interpretation: If the correlation is casued by random reasons (null hypothesis), there is a 95% chance of the t-score lies in the green part. Given that the our score lies far from the green part, it’s uper unlikely that our data is just random.

Takeaway: Given that p<0.05 and the visualization above, we can reject the null hypothesis, and we can conclude that whether living in urban/rural area could have an influence on the level of trust in other people inference.