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

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.

table(ess$brncntr)
## 
##      1      2      7      8      9 
## 443915  45887     78    108    567
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_data <- switzerland_data

mytable <- table(tab_data$brncntr, tab_data$educ_level)
rsums <- rowSums(mytable)
csums <- colSums(mytable)
N <- sum(mytable)

ptable <- tcrossprod(rsums/N, csums/N)
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
print(ptable)
##            [,1]      [,2]
## [1,] 0.05206627 0.1764393
## [2,] 0.17578931 0.5957051
ftable <- N * ptable
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftable)
##           [,1]      [,2]
## [1,]  881.1175  2985.882
## [2,] 2974.8825 10081.118
alpha <- 0.05 
c_value <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_value, 3), "\n")
## Critical Value: 3.841
teststat <- sum((mytable - ftable)^2 / ftable)
cat("Pearson's X^2:", round(teststat, 4), "\n")
## Pearson's X^2: 65.1218

Interpretation: since the X^2 value is larger than the critical value of 3.841, there is a statistically significant association between being born in the country one lives in and education level.

p_value <- pchisq(teststat, df = 1, lower.tail = F)
cat("p-value:", round(p_value, 4), "\n")
## p-value: 0
cat("Chi-squared test result:\n")
## Chi-squared test result:
print(chisq.test(mytable, correct = F))
## 
##  Pearson's Chi-squared test
## 
## data:  mytable
## X-squared = 65.122, df = 1, p-value = 7.041e-16

Interpretation: The p-value is represented in scientific notation, which means that it is very close to 0. We can reject the null hypothesis, and the two variables are dependent rather than independent. When paired with the X^2 value of 65.122 which is much larger than the critical value of 3.841, we can state that the two variables have a statistically significant association.

Main takeaways: If the X^2 value is significantly higher than the critical value, it is likely that the two variables are not independent. Similarly, f the p-value is lower than the significance level, it is likely that the two variables are not independent. The closer the p-value is to 0, the stronger the indication that there is a statistically significant association.

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.

table(ess$gincdif)
## 
##      1      2      3      4      5      7      8      9 
## 147968 204208  70201  47040  11323    492   8673    650
netherlands_data <- ess %>%
  filter(cntry == "NL") %>%
  mutate(
    gincdif = case_when(
      gincdif == 1 ~ "Agree strongly",
      gincdif == 2 ~ "Agree",
      gincdif == 3 ~ "Neither agree nor disagree", 
      gincdif == 4 ~ "Disagree",
      gincdif == 5 ~ "Disagree strongly",
      gincdif %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(gincdif)
    )
  )

table(netherlands_data$gincdif)
## 
##                      Agree             Agree strongly 
##                       7894                       2896 
##                   Disagree          Disagree strongly 
##                       3681                        543 
## Neither agree nor disagree 
##                       3142
netherlands_data <- netherlands_data %>%
    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_))

table(netherlands_data$geo)
## 
## Rural Urban 
## 12681  5623

Step 1: calculate 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 
##  8.176048

Step 2: simulate the 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.

Step 3: calculate the p-value

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

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

Step 4: visualize

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 3.00 
##  2         2 6.30 
##  3         3 0.741
##  4         4 3.01 
##  5         5 0.599
##  6         6 5.02 
##  7         7 1.57 
##  8         8 6.33 
##  9         9 3.61 
## 10        10 3.83 
## # ℹ 990 more rows

Interpretation:

Step 1: The X^2 value of 8.176 is a little larger than the critical value of 3.841. This shows that there could be a correlation between the two, but it is not very obvious.

Step 3: The p-value is 0.162, which is greater than the significance level of 0.05. Thereform, we have failed to reject the null hypothesis, and there is insufficient evidence to show that people in urban and rural areas have different views on whether the government should reduce differences in income levels.

Step 4: The distributions are right-skewed, and the test statistic overlaps with the null distribution. This is proof that we cannot reject the null hypothesis, and the two variables are likely independent.

Key takeaways:

Step 1: According to the table from the lecture slides, a Pearson’s Chi-squared test should be used for this data. This was initially confusing because I did not realize that the type of test could be changed, so it took some trial and error, but this information will be useful for the research project.

Step 4: When the test statistic overlaps with the null distribution in the visual, this is evidence that the null hypothesis cannot be rejected. When the two do not overlap, this is evidence that the null hypothesis can be rejected.

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.

Explanatory variable: rlgdnm - Religion or denomination belonging to at present

Outcome variable: ipsuces - Important to be successful and that people recognize achievements

Potential research question: Does the personal value of being successful and having others recognize one’s achievements correspond with religious domination?

Typically, a person’s values and morals are heavily affected by their religion and the values of that religion. I would like to take a closer look at that idea, so I have chosen the value of individual success for my outcome variable, and compared it to religious domination as an explanatory variable. I hope to compare my outcome variable to each of the 8 religious dominations within the rlgdnm variable, and analyze the categories individually. If this question is too broad, I will recode the rlgdnm variable to focus on a single religious denomination.

table(ess$rlgdnm)
## 
##      1      2      3      4      5      6      7      8     66     77     99 
## 145427  58582  48696   6415  12155  17568   1517   1401 182675    866   1738
table(ess$ipsuces)
## 
##      1      2      3      4      5      6      7      8      9 
##  48710 115969 115970  82711  68279  18852   1573   5733   4692
netherlands_data <- ess %>%
  filter(cntry == "NL") %>%
  mutate(
    rlgdnm = case_when(
      rlgdnm == 1 ~ "Roman Catholic",
      rlgdnm == 2 ~ "Protestant",
      rlgdnm == 3 ~ "Eastern Orthodox",
      rlgdnm == 4 ~ "Other Christian denomination",
      rlgdnm == 5 ~ "Jewish",
      rlgdnm == 6 ~ "Islam",
      rlgdnm == 7 ~ "Eastern religions",
      rlgdnm == 8 ~ "Other Non-Christian religions",
      rlgdnm %in% c(66, 77, 99) ~ NA_character_,
      TRUE ~ as.character(rlgdnm)
    ),
    ipsuces = case_when(
      ipsuces == 1 ~ "Very much like me",
      ipsuces == 2 ~ "Like me",
      ipsuces == 3 ~ "Somewhat like me",
      ipsuces == 4 ~ "A little like me",
      ipsuces == 5 ~ "Not like me",
      ipsuces == 6 ~ "Not like me at all",
      ipsuces %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(ipsuces)
    )
  )

Step 1: calculate test statistic

test_stat_v2 <- netherlands_data %>%
  specify(explanatory = rlgdnm,
          response = ipsuces) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "Chisq") 
## Warning: Removed 11498 rows containing missing values.
print(test_stat_v2$stat)
## X-squared 
##  259.9437

Step 2: simulate null distribution

null_distribution_v2 <- netherlands_data %>%
  specify(explanatory = rlgdnm,
          response = ipsuces) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "Chisq")
## Warning: Removed 11498 rows containing missing values.

Step 3: calculate the p-value

p_val <- null_distribution_v2 %>% 
  get_pvalue(obs_stat = test_stat_v2, 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

Step 4: visualize

null_distribution %>%
  visualize() +
  shade_p_value(obs_stat = test_stat_v2, 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 3.00 
##  2         2 6.30 
##  3         3 0.741
##  4         4 3.01 
##  5         5 0.599
##  6         6 5.02 
##  7         7 1.57 
##  8         8 6.33 
##  9         9 3.61 
## 10        10 3.83 
## # ℹ 990 more rows

X^2 = 259.944

p-value = 0

Interpretation: The x^2 value is very high, while the p-value is reported as 0, or else is very close to zero. The visualization indicates that the test statistic does not overlap with the null distribution, so we can confidently reject the null hypothesis. There is likely a strong association between the explanatory and outcome variables.

Takeaways: If a p-value is reported as 0 with the infer package, it is likely that only a small number of reps have been generated to form the null distribution. Regardless, in this case the p-value is very close to 0. This relationship between variables will be interesting to pursue further!