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"
library(fst)
ess <- read_fst("All-ESS-Data.fst")
switzerland_data <- ess %>%
  filter(cntry == "CH") %>%
  mutate(
    clsprty = case_when(
      clsprty == 1 ~ "Yes", 
      clsprty == 2 ~ "No",
      clsprty %in% c(7, 8, 9) ~ NA_character_,
      TRUE ~ as.character(clsprty)
    ),
    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)
    )
  )
switzerland_data <- switzerland_data %>%
  mutate(born_in_country = recode(brncntr,
                                  `1` = "Yes",
                                  `2` = "No",
                                  `7` = NA_character_,
                                  `8` = NA_character_,
                                  `9` = NA_character_))

netherlands_data <- ess %>% 
  filter(cntry == "NL") %>%
  mutate(
    domicil = recode(as.character(domicil), 
                      '1' = "Urban", 
                      '2' = "Urban", 
                      '3' = "Rural", 
                      '4' = "Rural", 
                      '5' = "Rural",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_),

    
                  gincdif = case_when(
                     gincdif == 1 ~ "Agree", 
                     gincdif == 2 ~ "Agree", 
                     gincdif == 3 ~ "Disagree", 
                     gincdif == 4 ~ "Disagree", 
                     gincdif == 5 ~ "Disagre",
                     gincdif %in% c(7,8,9) ~ NA_character_,
                    TRUE ~ as.character(gincdif)
                  )
)
netherlands_data <- netherlands_data %>% filter(!is.na(domicil))
netherlands_data <- netherlands_data %>% filter(!is.na(gincdif))

poland_data <- ess %>%
  filter(cntry == "PL") %>%
  mutate(
    netusoft = recode(as.character(netusoft), 
                      '1' = "No", 
                      '2' = "No", 
                      '3' = "No", 
                      '4' = "Yes", 
                      '5' = "Yes",
                      '7' = NA_character_,
                      '8' = NA_character_,
                      '9' = NA_character_),

     happy = case_when(
                     happy == 1 ~ "Extremely unhappy", 
                     happy == 2 ~ "Often unhappy", 
                     happy == 3 ~ "Frequently unhappy", 
                     happy == 4 ~ "Occasionally unhappy", 
                     happy == 5 ~ "Not happy or unhappy",
                     happy == 6 ~ "Somewhat happy",
                     happy == 7 ~ "Occasionally happy",
                     happy == 8 ~ "Frequently happy",
                     happy == 9 ~ "Often happy",
                     happy == 10 ~ "Extremely happy", 
                     happy %in% c(7,8,9) ~ NA_character_,
                    TRUE ~ as.character(happy)
                  )
)

Task 1

unique(switzerland_data$brncntr)
## [1] 2 1 7 8
unique(switzerland_data$educ_level)
## [1] "BA"    "No BA"
switzerland_data <- switzerland_data %>% filter(!is.na(brncntr))
switzerland_data <- switzerland_data %>% filter(!is.na(educ_level))
unique(switzerland_data$brncntr)
## [1] 2 1 7 8
table(switzerland_data$brncntr)
## 
##     1     2     7     8 
## 13056  3867     1     1
unique(switzerland_data$educ_level)
## [1] "BA"    "No BA"
table(switzerland_data$educ_level)
## 
##    BA No BA 
##  3856 13069
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,] 1.757478e-01 5.956555e-01
## [2,] 5.205397e-02 1.764246e-01
## [3,] 1.346107e-05 4.562312e-05
## [4,] 1.346107e-05 4.562312e-05
ftab <- N * ptab
cat("Table of Expected Frequencies:\n")
## Table of Expected Frequencies:
print(ftab)
##              [,1]         [,2]
## [1,] 2974.5309306 1.008147e+04
## [2,]  881.0134121 2.985987e+03
## [3,]    0.2278287 7.721713e-01
## [4,]    0.2278287 7.721713e-01
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.7174
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 = 65.717, df = 3, p-value = 3.523e-14

Since the chi-squared test statistic is 65.7174 which exceeds 3.841 (critical value), meaning that there is a statistically significant association between whether someone was born in Switzerland and one’s educational level. Thus, the probability of being born in Switzerland is not the same across different education levels. The p-value is =3.523e-14 which is quite close to 0, meaning there is a strong evidence to suggest that there is a significant association between the two variables in mytab.

Task 2

test_stat <- netherlands_data %>%
  specify(explanatory = domicil,
          response = gincdif) %>%
  hypothesize(null = "independence") %>%
  calculate(stat = "Chisq") 
print(test_stat$stat)
## X-squared 
##  4.224274
null_distribution <- netherlands_data %>%
  specify(explanatory = domicil,
          response = gincdif) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "Chisq")
p_val <- null_distribution %>%
  get_pvalue(obs_stat = test_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1   0.244
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: domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1 1.41  
##  2         2 3.02  
##  3         3 8.10  
##  4         4 2.65  
##  5         5 3.39  
##  6         6 8.59  
##  7         7 0.187 
##  8         8 0.0183
##  9         9 1.32  
## 10        10 4.22  
## # ℹ 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: domicil (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1 1.41  
##  2         2 3.02  
##  3         3 8.10  
##  4         4 2.65  
##  5         5 3.39  
##  6         6 8.59  
##  7         7 0.187 
##  8         8 0.0183
##  9         9 1.32  
## 10        10 4.22  
## # ℹ 990 more rows

From the bar graph, I can conclude that people that live in urban areas agree that government should reduce differences in income levels.

Task 3

test_stat <- poland_data %>%
  specify(explanatory = netusoft, 
  response = happy) %>%
  hypothesize(null = "independence") %>%
  calculate(stat = "chisq")
## Warning: Removed 12461 rows containing missing values.
  test_stat$stat
## X-squared 
##  83.12666
  null_distribution <- poland_data %>%
  specify(explanatory = netusoft,
          response = happy) %>%
  hypothesize(null = "independence") %>%
  generate(reps = 1000, type = "permute") %>%
  calculate(stat = "chisq")
## Warning: Removed 12461 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.
  p_val
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0
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: happy (factor)
## Explanatory: netusoft (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 13.5 
##  2         2 16.3 
##  3         3 12.6 
##  4         4 14.5 
##  5         5  8.87
##  6         6  6.64
##  7         7 12.3 
##  8         8 18.7 
##  9         9 14.9 
## 10        10 13.4 
## # ℹ 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: happy (factor)
## Explanatory: netusoft (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1 13.5 
##  2         2 16.3 
##  3         3 12.6 
##  4         4 14.5 
##  5         5  8.87
##  6         6  6.64
##  7         7 12.3 
##  8         8 18.7 
##  9         9 14.9 
## 10        10 13.4 
## # ℹ 990 more rows

I would like to consider the research question: What is the relationship between happiness and internet usage in Poland? Based on the bar graph, people that use the internet more often in Poland are relatively not that happy.