Setting up the environment

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 - Setting Up Data

switzerland_data <- ess %>%
  filter(cntry == "CH") %>%
  
  mutate(
    edulvla = case_when(
      essround < 5 & edulvla == 55 ~ NA_real_,
      TRUE ~ edulvla
    ),
    
    # Re-coding education 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"
    ),
    
    brncntr = recode(brncntr,
                                  `1` = "Yes",
                                  `2` = "No",
                                  `7` = NA_character_,
                                  `8` = NA_character_,
                                  `9` = NA_character_)
    )
table(switzerland_data$brncntr)
## 
##    No   Yes 
##  3867 13056
unique(switzerland_data$educ_level)
## [1] "BA"    "No BA"
unique(switzerland_data$brncntr)
## [1] "No"  "Yes" NA
switzerland_data <- switzerland_data %>% filter(!is.na(brncntr))

unique(switzerland_data$brncntr)
## [1] "No"  "Yes"
table(switzerland_data$brncntr)
## 
##    No   Yes 
##  3867 13056

Task 1 - Expected Proportions and Frequencies

tab_dat <- switzerland_data

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

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

Task 1 - Pearson’s Chi-squared Statistic & 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 Output / Discussion of Results: The observed Pearson’s X^2 (65.122) is greater than the critical value (3.841 ) which suggests a meaningful relationship worth exploring hoever the p-value is (7.041e-16) which is greater than 0.05, meaning that we fail to reject the null hypothesis.

Task 2

netherlands_data <- ess %>%
  filter(cntry == "NL") %>%
  
  mutate(
    domicil = recode(as.character(domicil), 
                      '1' = "Urban", 
                      '2' = "Peri-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_)
    )
tab_dat <- netherlands_data

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

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]       [,3]        [,4]       [,5]
## [1,] 0.04495550 0.01646924 0.02095567 0.003095465 0.01788301
## [2,] 0.30163846 0.11050387 0.14060651 0.020769678 0.11998984
## [3,] 0.08835171 0.03236725 0.04118449 0.006083563 0.03514574
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##           [,1]      [,2]      [,3]      [,4]      [,5]
## [1,]  815.0882  298.6038  379.9473  56.12388  324.2368
## [2,] 5469.0069 2003.5456 2549.3367 376.57504 2175.5357
## [3,] 1601.9049  586.8505  746.7160 110.30109  637.2275
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
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 24.8154
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 = 24.815, df = 8, p-value = 0.001671

Interpretation of Output / Discussion of Results: Since the observed Pearson’s X^2 (24.815) which is creater than the critical value (3.841) and the p-value (0.001671) is very small and less than 0.05, we reject the null hypothesis, suggesting a significant association between the two variables (meaning that they are not likely independent).

Task 3:

The research question that I would like to consider is: Does more social interaction increase a person’s sympathy for people in the United Kingdom? The explantory variable I plan to use for this is sclact (take part in social activities compared to others the same age) and ipudrst (important to understand different people). sclact would be the explanatory variable and then ipudrst would be the outcome variable.

Task 3 - Codes

gb_data <- ess %>%
  filter(cntry == "GB") %>%
  
  mutate(
    sclmeet = recode(as.character(sclmeet), 
                      '1' = "Never", 
                      '2' = "Less than once a month", 
                      '3' = "Once a month", 
                      '4' = "Several times a month", 
                      '5' = "Once a week",
                      '6' = "Several times a week",
                      '7' = "Every day",
                      '77' = NA_character_,
                      '88' = NA_character_,
                      '99' = NA_character_),
    
    ipudrst = recode(as.character(ipudrst), 
                      '1' = "Very much like me", 
                      '2' = "Like me",
                      '3' = "Somewhat like me", 
                      '4' = "A little like me", 
                      '5' = "Not like me",
                      '6' = "   Not like me at all",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_)
    )
tab_dat <- gb_data

mytab <- table(tab_dat$sclmeet, tab_dat$ipudrst)

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]        [,3]        [,4]        [,5]        [,6]
## [1,] 0.0007575602 0.014157340 0.066331690 0.004844215 0.026730059 0.029197342
## [2,] 0.0004174151 0.007800685 0.036548715 0.002669159 0.014728244 0.016087715
## [3,] 0.0001072906 0.002005054 0.009394323 0.000686069 0.003785684 0.004135116
## [4,] 0.0004991230 0.009327648 0.043703029 0.003191640 0.017611258 0.019236843
## [5,] 0.0011496537 0.021484812 0.100663253 0.007351455 0.040564844 0.044309129
## [6,] 0.0007807934 0.014591524 0.068365983 0.004992780 0.027549829 0.030092780
## [7,] 0.0016224109 0.030319734 0.142057702 0.010374499 0.057245801 0.062529800
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##           [,1]      [,2]      [,3]      [,4]       [,5]       [,6]
## [1,] 15.479984 289.29108 1355.4217  98.98669  546.20202  596.61848
## [2,]  8.529461 159.39919  746.8364  54.54160  300.95693  328.73637
## [3,]  2.192375  40.97127  191.9636  14.01913   77.35666   84.49697
## [4,] 10.199080 190.60115  893.0277  65.21797  359.86845  393.08564
## [5,] 23.492023 439.02065 2056.9529 150.21963  828.90203  905.41274
## [6,] 15.954732 298.16321 1396.9905 102.02246  562.95322  614.91588
## [7,] 33.152344 619.55344 2902.8071 211.99251 1169.76069 1277.73392
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
test_stat <- sum((mytab - ftab)^2 / ftab)
cat("Pearson's X^2:", round(test_stat, 4), "\n")
## Pearson's X^2: 64.7138
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))
## Warning in chisq.test(mytab, correct = F): Chi-squared approximation may be
## incorrect
## 
##  Pearson's Chi-squared test
## 
## data:  mytab
## X-squared = 64.714, df = 30, p-value = 0.0002386

Interpretation of Output / Discussion of Results: Since the observed Pearson’s X^2 (64.714) is less than the critical value (3.841) and the p-value (0.0002386) which is less than 0.05, we reject the null hypothesis and it suggests that tehre might be a significant association between the two variables.