SETUP

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

The critical value is 3.841 & Pearson’s chi-squared statistic is 65.1218. As the chi-squared well exceeds the critical value the null hypotheses is rejected and there is statistically significant association between being born in Switzerland and education level. This means that the level of education is different for whether a person was born in Switzerland or not.

The p-value is 7.041e-16 which is very close to 0 and the null hypothesis (ie the two variables are independent of each other) can be rejected. There’s evidence to suggest that there’s a significant association between level of education and whether the survey respondant was born in Switzerland or not.

switzerland_data <- ess %>%
  filter(cntry == "CH") %>%

  mutate(
    born_in_country = recode(brncntr,
                                  `1` = "Yes",
                                  `2` = "No",
                                  `7` = NA_character_,
                                  `8` = NA_character_,
                                  `9` = NA_character_
    ),

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

switzerland_data <- switzerland_data %>% filter(!is.na(born_in_country))
switzerland_data <- switzerland_data %>% filter(!is.na(educ_level))

table(switzerland_data$born_in_country)
## 
##    No   Yes 
##  3867 13056
table(switzerland_data$educ_level)
## 
##    BA No BA 
##  3856 13067
unique(switzerland_data$born_in_country)
## [1] "No"  "Yes"
unique(switzerland_data$educ_level)
## [1] "BA"    "No BA"
task1_tab <- switzerland_data

mytab <- table(task1_tab$educ_level, task1_tab$born_in_country)

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.1757893
## [2,] 0.17643931 0.5957051
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##           [,1]      [,2]
## [1,]  881.1175  2974.882
## [2,] 2985.8825 10081.118
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: 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

TASK 2

The independent variable is domicil which is a nominal categorical variable that I coded into two categories (Urban and Rural). The dependent variable is gincdif, how much do respondents agree that the government should equalize income, which is also a nominal categorical variable with 5 categories. Therefor the appropriate test is the chi-square test of independence.

The critical value is 3.841 & Pearson’s chi-squared statistic is 8.176. The chi-squared only slightly exceeds the critical value, but it does exceed this threshold. There is a slight statistical significance between living in an urban versus rural area and thinking the government should equalize income levels.

The p-value is 0.08534 which is over the threshold of 0.05 and the null hypothesis cannot actually be rejected, there is not enough evidence/data to suggest that there’s a significant association between level of education and whether the survey respondent was born in Switzerland or not.

The end result is that the null hypothesis cannot be rejected because there isn’t enough data, as evidenced by the p-value.

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

  mutate(
    gincdif = case_when(
      gincdif == 1 ~ "Strongly Agree",
      gincdif == 2 ~ "Agree",
      gincdif == 3 ~ "Neither Agree not Disagree",
      gincdif == 4 ~ "Disagree",
      gincdif == 5 ~ "Strongly Disagree",
      gincdif %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(gincdif)
    ),

    domicil = case_when(
      domicil == 1 ~ "Urban",
      domicil == 2 ~ "Urban",
      domicil == 3 ~ "Rural",
      domicil == 4 ~ "Rural",
      domicil == 5 ~ "Rural",
      domicil %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(domicil)
    )
  )

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

table(netherlands_data$gincdif)
## 
##                      Agree                   Disagree 
##                       7886                       3676 
## Neither Agree not Disagree             Strongly Agree 
##                       3137                       2889 
##          Strongly Disagree 
##                        543
table(netherlands_data$domicil)
## 
## Rural Urban 
## 12574  5557
unique(netherlands_data$gincdif)
## [1] "Agree"                      "Disagree"                  
## [3] "Neither Agree not Disagree" "Strongly Agree"            
## [5] "Strongly Disagree"
unique(netherlands_data$domicil)
## [1] "Urban" "Rural"
task2_tab <- netherlands_data

mytab <- table(task2_tab$gincdif, task2_tab$domicil)

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.30163846 0.133307214
## [2,] 0.14060651 0.062140162
## [3,] 0.11998984 0.053028751
## [4,] 0.11050387 0.048836488
## [5,] 0.02076968 0.009179028
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##          [,1]      [,2]
## [1,] 5469.007 2416.9931
## [2,] 2549.337 1126.6633
## [3,] 2175.536  961.4643
## [4,] 2003.546  885.4544
## [5,]  376.575  166.4250
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: 8.176
p_val <- pchisq(test_stat, df = 1, lower.tail = F)
cat("p-value:", round(p_val, 4), "\n")
## p-value: 0.0042
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 = 8.176, df = 4, p-value = 0.08534

TASK 3

My research question is “how does gender relate to recent ethical consumer purchases in Poland?”

The independent variable is gndr which is a nominal categorical variable of gender with the two categories of men and women. The dependent variable is bghtprd, have you bought a product within the last 12 months for political/ethical/environmental reasons, which is also a nominal categorical variable with 2 categories: Yes and No. Therefor the appropriate test is the two sample Z test.

The p-value is 0.022 which is below the threshold of 0.05 meaning that there is enough data to reject the null hypothesis. The z-value (red line) is 2.364509 which is outside of the confidence intervals of 95% confidence and as well, the null hypothesis can be rejected.

Overall there is statistical significance between the gender of the respondent and whether they purchased a product within the last 12 months for political/ethical/environmental reasons.

poland_data <- ess %>%
  filter(cntry == "PL") %>%

  mutate(
    bghtprd = case_when(
      bghtprd == 1 ~ "Yes",
      bghtprd == 2 ~ "No",
      bghtprd %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(bghtprd)
    ),

    gndr = case_when(
      gndr == 1 ~ "Men",
      gndr == 2 ~ "Women",
      gndr %in% c(9) ~ NA_character_,
      TRUE ~ as.character(gndr)
    )
  )

poland_data <- poland_data %>% filter(!is.na(bghtprd))
poland_data <- poland_data %>% filter(!is.na(gndr))

table(poland_data$bghtprd)
## 
##   No  Yes 
## 1876  220
table(poland_data$gndr)
## 
##   Men Women 
##  1025  1071
unique(poland_data$bghtprd)
## [1] "No"  "Yes"
unique(poland_data$gndr)
## [1] "Men"   "Women"
task3 <- poland_data %>%
  specify(explanatory = gndr,
          response = bghtprd,
          success = "No") %>%
  hypothesize(null = "independence") %>%
  calculate(stat = "z", order = c("Men", "Women"))

print(task3$stat)
## [1] 2.364509
null_task3 <- poland_data %>%
  specify(explanatory = gndr,
          response = bghtprd,
          success = "No") %>%
  hypothesize(null = "independence") %>%
    generate(reps = 1000, type = "permute") %>%
  calculate(stat = "z", order = c("Men", "Women"))

p_val <- null_task3 %>%
  get_pvalue(obs_stat = task3, direction = "two-sided")

p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.006
null_task3 %>%
  visualize() +
  shade_p_value(obs_stat = task3, direction = "two-sided")

null_task3
## Response: bghtprd (factor)
## Explanatory: gndr (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 1
##       stat
##      <dbl>
##  1  0.654 
##  2 -2.20  
##  3 -0.202 
##  4  1.08  
##  5  0.369 
##  6 -1.63  
##  7  1.08  
##  8  0.0835
##  9  0.511 
## 10  0.654 
## # ℹ 990 more rows
conf_int <- null_task3 %>%
  get_confidence_interval(level = 0.95, type = "percentile")


null_task3 %>%
  visualize() +
  shade_p_value(obs_stat = task3, direction = "two-sided") +
  shade_confidence_interval(endpoints = conf_int)

null_task3
## Response: bghtprd (factor)
## Explanatory: gndr (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 1
##       stat
##      <dbl>
##  1  0.654 
##  2 -2.20  
##  3 -0.202 
##  4  1.08  
##  5  0.369 
##  6 -1.63  
##  7  1.08  
##  8  0.0835
##  9  0.511 
## 10  0.654 
## # ℹ 990 more rows