Setup

# 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

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.

ess$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
  ess$year[ess$essround == i] <- replacements[i]
}


switz_data <- ess %>% # Start with the original 'ess' dataset
  filter(cntry == "CH")
# Re-coding education
switz_data <- switz_data %>%
  mutate(
    # Set 'other' to NA for rounds 1-4
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    # Set 'other' to NA for rounds 5 and later
    edulvlb = case_when(
      essround >= 5 & edulvlb == 5555 ~ NA_real_,
      TRUE ~ edulvlb
    ),
    # Create educ_level column
    educ_level = case_when(
      essround < 5 & edulvla == 5 ~ "BA",
      essround >= 5 & edulvlb > 600 ~ "BA",
      TRUE ~ "No BA"
    )
  )

# View the table of educ_level
table(switz_data$educ_level)
## 
##    BA No BA 
##  3856 13069
# renaming to born_in_country and recoding to Y/N
switz_data <- switz_data %>%
  mutate(born_in_country = recode(brncntr,
                                  `1` = "Yes",
                                  `2` = "No",
                                  `7` = NA_character_,
                                  `8` = NA_character_,
                                  `9` = NA_character_))

# always check what you did
table(switz_data$born_in_country)
## 
##    No   Yes 
##  3867 13056
unique(switz_data$gndr)
## [1] 2 1 9
switz_data <- switz_data %>% filter(!is.na(born_in_country))
switz_data <- switz_data %>% filter(!is.na(educ_level))
## Not necessary, but always good to rename when doing operations so you can backtrack to clean dataset
tab_dat <- switz_data

# Create a crosstable and save it into the object mytab
mytab <- table(tab_dat$born_in_country, tab_dat$educ_level)

# Calculate row-wise sums of counts in table 
rsums <- rowSums(mytab)

# Calculate column-wise sums of counts in table
csums <- colSums(mytab)

# Get the total count of the table (N)
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 # significance level
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841

The critical value for independence is 3.841, meaning that if the chi-squared test statistic computes a number larger than this, then the null hypothesis with the 0.5 significance level is rejected.

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

Interpretation: The Pearson’s chi-squared statistic of 65.1218 is substantially larger than the critical value of 3.841, suggesting a significant departure from the expected frequencies. This is evidence against the null hypothesis of independence. With the p value being 0, it shows strong evidence against the null hypothesis, supporting the idea that there is a significant association between the two categorical variables born in country and education levels.

##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 %>% # Start with the original 'ess' dataset
  filter(cntry == "NL") %>%
    mutate(geo = recode(as.character(domicil), 
                        '1' = "Urban",
                        '2' = "Peri-Urban", 
                        '3' = "Rural",
                        '4' = "Rural",
                        '5' = NA_character_,
                        '6' = NA_character_,
                        '7' = NA_character_),
           gincdif = case_when(
             gincdif == '1' ~ "Agree strongly",
             gincdif == '2' ~ "Agree",
             gincdif == '3' ~ "Neither agree nor disagree",
             gincdif == '4' ~ "Disagree",
             gincdif == '5' ~ "Disagree strongly",
             gincdif == '6' ~ NA_character_, 
             gincdif == '7' ~ NA_character_, 
             gincdif == '8' ~ NA_character_, 
             gincdif == '9' ~ NA_character_, 
           )
    )
unique(netherlands_data$geo)
## [1] "Urban"      "Peri-Urban" NA           "8"          "Rural"     
## [6] "9"
unique(netherlands_data$gincdif)
## [1] "Agree"                      "Disagree"                  
## [3] "Neither agree nor disagree" "Agree strongly"            
## [5] NA                           "Disagree strongly"
netherlands_data <- netherlands_data %>% filter(!is.na(geo))
netherlands_data <- netherlands_data %>% filter(!is.na(gincdif))
test_stat <- netherlands_data %>%
  specify(explanatory = geo, # change variable name for explanatory variable
          response = gincdif) %>% # change variable name for outcome of interest
  hypothesize(null = "independence") %>%
  calculate(stat = "Chisq") # replace in between quotation marks appropriate test statistic
print(test_stat$stat)
## X-squared 
##  31.76653
null_distribution <- netherlands_data %>%
  specify(explanatory = geo,
          response = gincdif) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
  calculate(stat = "Chisq")
p_val <- null_distribution %>% # replace name here if you assigned something other than null_distribution above
  get_pvalue(obs_stat = test_stat, direction = "two-sided") # would only replace test_stat if assigned another name in Step 1
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.038
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 10.7 
##  2         2 15.0 
##  3         3 15.1 
##  4         4 11.9 
##  5         5  9.77
##  6         6 11.6 
##  7         7 12.1 
##  8         8  8.79
##  9         9 11.8 
## 10        10 17.4 
## # ℹ 990 more rows

With the p-value being 0.024, I would reject the null hypothesis of independence at the 0.05 significance level because there is evidence to suggest a significant association between the type of living (urban or rural) and the opinion that the government should reduce differences in income levels.

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

A research Question I would like to consider is the relationship between association of religion (explanatory) and politics, more specifically if they care about politics enough to vote, or maybe the trust religious people have in politicians and government. PICK ONE ASAP

romania_data <- ess %>% # Start with the original 'ess' dataset
  filter(cntry == "RO") %>%
    mutate(rlg = recode(as.character(rlgdnm), 
                        '1' = "Roman Catholic",
                        '2' = "Protestant", 
                        '3' = "Eastern Orthodox",
                        '4' = "Other Christian denomination",
                        '5' = "Jewish",
                        '6' = "Islam",
                        '7' = "Eastern religions",
                        '8' = "Other Non-Christian religions",
                        '66' = NA_character_,
                        '77' = NA_character_,
                        '99' = NA_character_),
           polintr = case_when(
             polintr == '1' ~ "Very interested",
             polintr == '2' ~ "Quite interested",
             polintr == '3' ~ "Hardly interested",
             polintr == '4' ~ "Not at all interested",
             polintr == '7' ~ NA_character_, 
             polintr == '8' ~ NA_character_, 
             polintr == '9' ~ NA_character_, 
           )
    )
test_stat <- romania_data %>%
  specify(explanatory = rlg, # change variable name for explanatory variable
          response = polintr) %>% # change variable name for outcome of interest
  hypothesize(null = "independence") %>%
  calculate(stat = "Chisq") # replace in between quotation marks appropriate test statistic
## Warning: Removed 216 rows containing missing values.
print(test_stat$stat)
## X-squared 
##  8.081659
null_distribution <- romania_data %>%
  specify(explanatory = rlg,
          response = polintr) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
  calculate(stat = "Chisq")
## Warning: Removed 216 rows containing missing values.
p_val <- null_distribution %>% # replace name here if you assigned something other than null_distribution above
  get_pvalue(obs_stat = test_stat, direction = "two-sided") 
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.124
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.

The p-value of 0.144 is greater the significance level of 0.05, meaning I do not have enough evidence to reject the null hypothesis at the 0.05 significance level and the test statistic score indicates I do not have enough evidence to reject the null hypothesis. Overall, here is not enough evidence to claim a significant association between the association with a religion and trust in politicians.