Setting up environment

# 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("/Users/paulcavaco/Desktop/Alyssa school/Homework 7/All-ESS-Data.fst")

Task 1

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)  
    ),
    trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
    
    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"
    ),
    
    gndr = case_when(
      gndr == 1 ~ "Male",
      gndr == 2 ~ "Female",
      gndr == 9 ~ NA_character_,
      TRUE ~ as.character(gndr)
    )
  )
unique(switzerland_data$gndr)
## [1] "Female" "Male"   NA
unique(switzerland_data$brncntr)
## [1] "No"  "Yes" NA
switzerland_data <- switzerland_data %>% filter(!is.na(brncntr))
switzerland_data <- switzerland_data %>% filter(!is.na(trstplt))
switzerland_data <- switzerland_data %>% filter(!is.na(educ_level))

unique(switzerland_data$brncntr)
## [1] "No"  "Yes"
table(switzerland_data$brncntr)
## 
##    No   Yes 
##  3570 12841
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.05018556 0.1673515
## [2,] 0.18051337 0.6019496
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##           [,1]     [,2]
## [1,]  823.5951 2746.405
## [2,] 2962.4049 9878.595
alpha <- 0.05
c_val <- qchisq(alpha, df = 1, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: 3.841
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 75.4503
# 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 = 75.45, df = 1, p-value < 2.2e-16

Task 2

netherlands_data <- ess %>%
  filter(cntry == "NL")
netherlands_data <- ess %>%
  filter(cntry == "NL")

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
netherlands_data <- netherlands_data %>% filter(!is.na(geo))
netherlands_data <- netherlands_data %>%
mutate(
    gincdif = case_when(
      gincdif == 1 ~ "Yes",  
      gincdif == 2 ~ "No",  
      gincdif %in% c(7, 8, 9) ~ NA_character_,  
      TRUE ~ as.character(gincdif)  
)
  )

netherlands_data <- netherlands_data %>% filter(!is.na(gincdif))

Step 1

test_stat <- netherlands_data %>%
  specify(explanatory = geo, 
          response = gincdif) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "Chisq")

print(test_stat$stat)
## X-squared 
##  8.176048

Step 2

null_distribution <- netherlands_data %>%
  specify(explanatory = geo,
          response = gincdif) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
calculate(stat = "Chisq")

Step 3

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

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

Step 4

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  2.75
##  2         2  4.60
##  3         3  6.89
##  4         4  3.80
##  5         5  7.65
##  6         6  3.92
##  7         7  7.81
##  8         8  1.82
##  9         9  4.04
## 10        10  5.55
## # ℹ 990 more rows
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.

null_distribution
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  2.75
##  2         2  4.60
##  3         3  6.89
##  4         4  3.80
##  5         5  7.65
##  6         6  3.92
##  7         7  7.81
##  8         8  1.82
##  9         9  4.04
## 10        10  5.55
## # ℹ 990 more rows

Task 2 Takeaways

It is clear that in both graphs, are information is heavily left-skewed. We can also see that our P-value tells us that our data is 0.204 deviations from the null hypothesis. However, because we know that our P-value is greater than 0.05, we fail to reject the null hypothesis and therefore come to the conclusion that there is no correlation in the Netherlands between the area in which you live in (Urban/Rural), and an individuals belief that their government should reduce differences in income levels.

Task 3

After looking at the relationship between place of residence and opinions on if the government should reduce differences in income levels in the Netherlands, I am curious to see if a nearby country such as Sweden, would have similar results between these two variables.

Step 1

sweden_data <- ess %>%
  filter(cntry == "SE")
sweden_data <- sweden_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(sweden_data$geo)
## 
## Rural Urban 
## 11559  6618
sweden_data <- sweden_data %>% filter(!is.na(geo))
sweden_data  <- sweden_data %>%
mutate(
    gincdif = case_when(
      gincdif == 1 ~ "Yes",  
      gincdif == 2 ~ "No",  
      gincdif %in% c(7, 8, 9) ~ NA_character_,  
      TRUE ~ as.character(gincdif)  
)
  )

sweden_data <- sweden_data %>% filter(!is.na(gincdif))

Step 1

test_stat <- sweden_data %>%
  specify(explanatory = geo, 
          response = gincdif) %>% 
  hypothesize(null = "independence") %>%
  calculate(stat = "Chisq")

print(test_stat$stat)
## X-squared 
##  110.6002

Step 2

null_distribution <- sweden_data %>%
  specify(explanatory = geo,
          response = gincdif) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>% 
  calculate(stat = "Chisq")

Step 3

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

Step 4

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 2.22 
##  2         2 4.34 
##  3         3 0.898
##  4         4 4.21 
##  5         5 6.56 
##  6         6 4.69 
##  7         7 0.978
##  8         8 3.36 
##  9         9 1.69 
## 10        10 6.94 
## # ℹ 990 more rows
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.

null_distribution
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 2.22 
##  2         2 4.34 
##  3         3 0.898
##  4         4 4.21 
##  5         5 6.56 
##  6         6 4.69 
##  7         7 0.978
##  8         8 3.36 
##  9         9 1.69 
## 10        10 6.94 
## # ℹ 990 more rows

Takeaways

Upon observation, both the Netherlands and Sweden seem to have heavily left-skewed graphs, however Sweden it a bit more left-skewed than the Netherlands. Similar to the Netherlands, Sweden’s P-value is also greater than 0.05 and therefore we still fail to reject the null hypothesis. With this information in mind, we can infer that due to the close proximity of the Netherlands and Sweden, they will tend to have similar results in terms of the relationship between place of residence and opinions on if the government should reduce differences in income levels.