SETTING UP WORKING DIRECTORY AND ENVIRONMENT

rm(list=ls()); gc()
##          used (Mb) gc trigger (Mb) limit (Mb) max used (Mb)
## Ncells 522605 28.0    1158447 61.9         NA   669420 35.8
## Vcells 962909  7.4    8388608 64.0      16384  1851667 14.2
setwd("~/Desktop/SOC202")
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"
# Loading dataset
ess <- read_fst("All-ESS-Data.fst")

CLEANING VARIABLES FOR PART C) CONTEXT

# Filtering for country and cleaning variables
sweden_data <- ess |>
  filter(cntry == "SE") |>
  mutate(
    happiness = case_when(
      happy %in%  0 ~ "Extremely unhappy",
      happy %in%  1:3 ~ "Unhappy",
      happy %in%  4:6 ~ "Average",
      happy %in%  7:9 ~ "Happy",
      happy %in% 10 ~ "Extremely happy",
      happy %in% c(77, 88, 99)  ~ NA_character_  
    ),
  polID = case_when(
      lrscale %in% 0:3 ~ "Left",                    
      lrscale %in% 7:10 ~ "Right",                     
      lrscale %in% 4:6 ~ "Moderate",                  
      lrscale %in% c(77, 88, 99) ~ NA_character_      
    ),
  marriage = case_when(
      marsts %in% 1:2 ~ "Legally married/registered civil union",                    
      marsts %in% 3:6 ~ "Not married/union dissolved",   
      marsts %in% c(66, 77, 88, 99) ~ NA_character_                
  ),
  income = case_when(
      hinctnta %in% 1:2 ~ "High",                    
      hinctnta %in% 9:10 ~ "Low",                     
      hinctnta %in% 3:8 ~ "Middle",  
      hinctnta %in% c(77, 88, 99) ~ NA_character_      
  ),
  discrimination = recode(dscrrce, '0' = 'Not marked', '1' = 'Marked'),
  )

# Making sure data is really cleaned
sweden_data <- sweden_data %>% filter(!is.na(polID))
sweden_data <- sweden_data %>% filter(!is.na(happiness))
sweden_data <- sweden_data %>% filter(!is.na(marriage))
sweden_data <- sweden_data %>% filter(!is.na(income))

# Converting factors/characters to numeric 
sweden_data <- sweden_data |>
  mutate(
    happy_num = as.numeric(factor(happiness, levels = c("Extremely unhappy", "Unhappy", "Average", "Happy", "Extremely happy"))),
    polID_num = as.numeric(factor(polID, levels = c("Left", "Moderate", "Right"))),
    marriage_num = as.numeric(factor(marriage, levels = c("Legally married/registered civil union", "Not married/union dissolved"))),
    income_num = as.numeric(factor(income, levels = c("High", "Middle", "Low"))),
    discrimination_num = as.numeric(dscrrce)
  )

# Producing first summary table
summary_table <- datasummary_skim(sweden_data %>% select(happy_num, polID_num, marriage_num, income_num, discrimination_num), output = "flextable")
## Warning: The histogram argument is only supported for (a) output types "default",
##   "html", "kableExtra", or "gt"; (b) writing to file paths with extensions
##   ".html", ".jpg", or ".png"; and (c) Rmarkdown, knitr or Quarto documents
##   compiled to PDF (via kableExtra)  or HTML (via kableExtra or gt). Use
##   `histogram=FALSE` to silence this warning.
summary_table

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

happy_num

5

0

3.9

0.6

1.0

4.0

5.0

polID_num

3

0

2.0

0.8

1.0

2.0

3.0

marriage_num

2

0

2.0

0.2

1.0

2.0

2.0

income_num

3

0

2.0

0.7

1.0

2.0

3.0

discrimination_num

2

0

0.0

0.1

0.0

0.0

1.0

# Relabelling Table
summary_table_v2 <- sweden_data |>
  rename(
    `Placement on left right political scale` = polID_num,
    `Reported levels of happiness` = happy_num,
    `Discrimination of respondent's group: colour or race` = discrimination_num,
    `Legal marital status` = marriage_num,
    `Household's total net income` = income_num
  )

# Producing first summary table version 2 
Sweden_summary_table <- datasummary_skim(summary_table_v2 |> select(`Placement on left right political scale`,`Reported levels of happiness`, `Discrimination of respondent's group: colour or race`, `Legal marital status`, `Household's total net income`), output = "flextable")
## Warning: The histogram argument is only supported for (a) output types "default",
##   "html", "kableExtra", or "gt"; (b) writing to file paths with extensions
##   ".html", ".jpg", or ".png"; and (c) Rmarkdown, knitr or Quarto documents
##   compiled to PDF (via kableExtra)  or HTML (via kableExtra or gt). Use
##   `histogram=FALSE` to silence this warning.
Sweden_summary_table <- add_header_lines(Sweden_summary_table, values = "Table 1. Descriptive statistics of main variables")

Sweden_summary_table

Table 1. Descriptive statistics of main variables

Unique (#)

Missing (%)

Mean

SD

Min

Median

Max

Placement on left right political scale

3

0

2.0

0.8

1.0

2.0

3.0

Reported levels of happiness

5

0

3.9

0.6

1.0

4.0

5.0

Discrimination of respondent's group: colour or race

2

0

0.0

0.1

0.0

0.0

1.0

Legal marital status

2

0

2.0

0.2

1.0

2.0

2.0

Household's total net income

3

0

2.0

0.7

1.0

2.0

3.0

# Showing categorical and numerical variables separately (not needed)
Sweden_summary_table_2 <- datasummary_skim(summary_table_v2  %>% dplyr::select(polID, marriage, income, discrimination), type = "categorical", title = "Table 1. Categorical Predictors Summary", output = "flextable")


Sweden_summary_table_2
Table 1. Categorical Predictors Summary

N

%

polID

Left

1021

26.0

Moderate

1690

43.1

Right

1210

30.9

marriage

Legally married/registered civil union

152

3.9

Not married/union dissolved

3769

96.1

income

High

901

23.0

Low

768

19.6

Middle

2252

57.4

discrimination

Marked

28

0.7

Not marked

3893

99.3

INFER PACKAGE FOUR STEPS FOR PART D) FINDINGS

# Step 1: Calculating test statistic
test_stat <- sweden_data |>
  specify(explanatory = polID, 
          response = happiness) |> 
  hypothesize(null = "independence") |>
  calculate(stat = "Chisq") 
print(test_stat$stat)
## X-squared 
##  46.36494
# Step 2: Simulating null distribution 
null_distribution <- sweden_data |>
  specify(explanatory = polID,
          response = happiness) |>
  hypothesize(null = "independence") |>
  generate(reps = 1000, type = "permute") |>
  calculate(stat = "Chisq")

# Step 3: Calculating p-value
p_value <- null_distribution |>
  get_pvalue(obs_stat = test_stat, direction = "greater") 
## 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_value
## # A tibble: 1 × 1
##   p_value
##     <dbl>
## 1       0
# Step 4: Visualizing test statistic and null distribution
null_distribution |>
  visualize() +
  shade_p_value(obs_stat = test_stat, direction = "greater")
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf

null_distribution
## Response: happiness (factor)
## Explanatory: polID (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate  stat
##        <int> <dbl>
##  1         1  8.61
##  2         2  2.57
##  3         3  8.49
##  4         4  6.58
##  5         5  5.71
##  6         6  4.46
##  7         7  7.13
##  8         8  6.31
##  9         9  3.49
## 10        10  5.07
## # ℹ 990 more rows