Setup

setwd("/Users/sophiafernandes/Desktop/SOC202 Folder")
getwd()
## [1] "/Users/sophiafernandes/Desktop/SOC202 Folder"
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer", "fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer")
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
## Loading required package: viridisLite
## 
## 
## Attaching package: 'flextable'
## 
## 
## The following object is masked from 'package:purrr':
## 
##     compose
## [[1]]
##  [1] "lubridate" "forcats"   "stringr"   "dplyr"     "purrr"     "readr"    
##  [7] "tidyr"     "tibble"    "ggplot2"   "tidyverse" "stats"     "graphics" 
## [13] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[2]]
##  [1] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [16] "datasets"     "methods"      "base"        
## 
## [[3]]
##  [1] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
##  [6] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [11] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [16] "datasets"     "methods"      "base"        
## 
## [[4]]
##  [1] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
##  [6] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [11] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [16] "utils"        "datasets"     "methods"      "base"        
## 
## [[5]]
##  [1] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[6]]
##  [1] "viridis"      "viridisLite"  "fst"          "RColorBrewer" "modelsummary"
##  [6] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [11] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [16] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [21] "methods"      "base"        
## 
## [[7]]
##  [1] "knitr"        "viridis"      "viridisLite"  "fst"          "RColorBrewer"
##  [6] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
## [11] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [16] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [21] "datasets"     "methods"      "base"        
## 
## [[8]]
##  [1] "rmarkdown"    "knitr"        "viridis"      "viridisLite"  "fst"         
##  [6] "RColorBrewer" "modelsummary" "lubridate"    "forcats"      "stringr"     
## [11] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [16] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [21] "utils"        "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[10]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "fst"          "RColorBrewer" "modelsummary" "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[11]]
##  [1] "questionr"    "ggridges"     "rmarkdown"    "knitr"        "viridis"     
##  [6] "viridisLite"  "fst"          "RColorBrewer" "modelsummary" "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[12]]
##  [1] "flextable"    "questionr"    "ggridges"     "rmarkdown"    "knitr"       
##  [6] "viridis"      "viridisLite"  "fst"          "RColorBrewer" "modelsummary"
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[13]]
##  [1] "infer"        "flextable"    "questionr"    "ggridges"     "rmarkdown"   
##  [6] "knitr"        "viridis"      "viridisLite"  "fst"          "RColorBrewer"
## [11] "modelsummary" "lubridate"    "forcats"      "stringr"      "dplyr"       
## [16] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [21] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"
ess <- read_fst("All-ESS-Data.fst")

Task 1

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

switzerland_data <- switzerland_data %>%
  mutate(
    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"
    )
  )

# Load necessary libraries
library(dplyr)

# Filter data for Switzerland
switzerland_data <- ess %>%
   filter(cntry == "CH")

# Mutate variables
switzerland_data <- switzerland_data %>%
  mutate(
    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"
    )
  )

# Display table for educ_level
table(switzerland_data$educ_level)
## 
##    BA No BA 
##  3856 13069
# Mutate brncntr_recode variable
switzerland_data <- switzerland_data %>%
     mutate(brncntr_recode = case_when(
         brncntr == 1 ~ 'yes',
         brncntr == 2 ~ 'no', 
     ))


table(switzerland_data$brncntr_recode)
## 
##    no   yes 
##  3867 13056
unique(switzerland_data$brncntr_recode)
## [1] "no"  "yes" NA
unique(switzerland_data$educ_level)
## [1] "BA"    "No BA"
switzerland_data <- switzerland_data %>% filter(!is.na(brncntr_recode))


unique(switzerland_data$brncntr_recode)
## [1] "no"  "yes"
# Create contingency table
tab_dat <- switzerland_data
mytab <- table(tab_dat$brncntr_recode, tab_dat$educ_level)
rsums <- rowSums(mytab)
csums <- colSums(mytab)
N <- sum(mytab)
ptab <- tcrossprod(rsums/N, csums/N)

# Display table of Expected Proportions
cat("Table of Expected Proportions:\n")
## Table of Expected Proportions:
print(ptab)
##            [,1]      [,2]
## [1,] 0.05206627 0.1764393
## [2,] 0.17578931 0.5957051
# Calculate 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
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
# Calculate p-value
p_val <- pchisq(test_stat, df = 1, lower.tail = FALSE)


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 = FALSE))
## 
##  Pearson's Chi-squared test
## 
## data:  mytab
## X-squared = 65.122, df = 1, p-value = 7.041e-16
## Interpretation of results: The small p value of ( 7.041×10 −16)  suggests that we can reject the null hypothesis.
#The chi-squared statistic (65.122) is significantly greater than the critical value (3.841) at the 0.05 significance level.
#There is strong evidence to conclude that there is a significant association or difference between the variables brncntr and education level
#Overall the association observed is unlikely to be due to random chance alone.

Task 2

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_))
netherlands_data <- netherlands_data %>%
mutate(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_))

table(netherlands_data$gincdif)
## 
##                      Agree             Agree strongly 
##                       7894                       2896 
##                   Disagree          Disagree strongly 
##                       3681                        543 
## Neither agree nor disagree 
##                       3142

Chisq Calculation

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

Visualization

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.

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 %>%
  print()
## Response: gincdif (factor)
## Explanatory: geo (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 7.43 
##  2         2 0.353
##  3         3 4.59 
##  4         4 1.20 
##  5         5 2.87 
##  6         6 2.79 
##  7         7 7.26 
##  8         8 1.47 
##  9         9 5.07 
## 10        10 4.20 
## # ℹ 990 more rows

#Interpretation: the p-value is 0.154, it is greater than the conventional significance level of 0.05, meaning there is not # sufficient evidence to reject the null hypothesis between the variables geo and gincdif. #The observed association in the data could occur by random chance.

Task 3

##My research question is is there a relationship between having a partner (married or in a civil partnership) (Explanatory varible) and overall happiness (outcome variable). I will explore this relationship in France.

france_data <- ess %>%
  filter(cntry == "FR") %>%
  mutate(
    maritalstat = recode(
      as.character(maritala),
      '1' = "Partnered",
      '2' = "Partnered",
      '3' = "Non Partnered",
      '4' = "Non Partnered",
      '5' = "Non Partnered",
      '6' = "Non Partnered",
      '7' = "Non Partnered",
      '8' = "Non Partnered",
      '9' = "Non Partnered",
      '77' = NA_character_,
      '88' = NA_character_,
      '99' = NA_character_
    )
  )
table(france_data$maritalstat)
## 
## Non Partnered     Partnered 
##          2004          2046
france_data <- france_data %>%
  mutate(
    happiness = recode(
      as.character(happy),
      '77' = NA_character_,
      '88' = NA_character_,
      '99' = NA_character_
    )
  )
table(france_data$happiness)
## 
##    0    1   10    2    3    4    5    6    7    8    9 
##   90   57 1622  185  346  514 2349 1869 4003 5591 2386
test_stat <- france_data %>%
  specify(
    explanatory = maritalstat,
    response = happiness
  ) %>%
  hypothesize(null = "independence") %>%
  calculate(stat = "Chisq")
## Warning: Removed 14994 rows containing missing values.
print(test_stat$stat)
## X-squared 
##  107.3595
null_distribution <- france_data %>%
  specify(
    explanatory = maritalstat,
    response = happiness
  ) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "Chisq")
## Warning: Removed 14994 rows containing missing values.
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.
print(p_val)
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0

Visualization

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.

print(null_distribution)
## Response: happiness (factor)
## Explanatory: maritalstat (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  2.85
##  2         2  9.94
##  3         3  3.73
##  4         4 10.9 
##  5         5 23.0 
##  6         6  9.80
##  7         7 15.0 
##  8         8  3.96
##  9         9  5.97
## 10        10  6.88
## # ℹ 990 more rows

Visualization of Confidence Intervals

## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.

##Takeaways: A p-value of 0 suggests strong evidence against the null hypothesis of independence. It indicates that the association observed between variable maritalstat and happiness is highly unlikely to be due to random chance. This means there is worthy further exploration between these variables in the country of france and that marriage status can possibly influence level of happiness. As well, the second graph shows that the p-value is outside the confidence interval, so it means that the observed result is statistically significant and rejects the null.