Setting up working directory and environment

rm(list=ls()); gc()
##          used (Mb) gc trigger (Mb) limit (Mb) max used (Mb)
## Ncells 522670 28.0    1158632 61.9         NA   669420 35.8
## Vcells 963363  7.4    8388608 64.0      16384  1851667 14.2
setwd("~/Desktop/SOC202")
packages <- c("tidyverse", "effects", "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: carData
## 
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
## 
## 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] "effects"   "carData"   "lubridate" "forcats"   "stringr"   "dplyr"    
##  [7] "purrr"     "readr"     "tidyr"     "tibble"    "ggplot2"   "tidyverse"
## [13] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"  
## [19] "base"     
## 
## [[3]]
##  [1] "modelsummary" "effects"      "carData"      "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[4]]
##  [1] "modelsummary" "effects"      "carData"      "lubridate"    "forcats"     
##  [6] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [11] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [16] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[5]]
##  [1] "RColorBrewer" "modelsummary" "effects"      "carData"      "lubridate"   
##  [6] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [11] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [16] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [21] "base"        
## 
## [[6]]
##  [1] "fst"          "RColorBrewer" "modelsummary" "effects"      "carData"     
##  [6] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [11] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [16] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [21] "methods"      "base"        
## 
## [[7]]
##  [1] "viridis"      "viridisLite"  "fst"          "RColorBrewer" "modelsummary"
##  [6] "effects"      "carData"      "lubridate"    "forcats"      "stringr"     
## [11] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [16] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [21] "utils"        "datasets"     "methods"      "base"        
## 
## [[8]]
##  [1] "knitr"        "viridis"      "viridisLite"  "fst"          "RColorBrewer"
##  [6] "modelsummary" "effects"      "carData"      "lubridate"    "forcats"     
## [11] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [16] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [21] "grDevices"    "utils"        "datasets"     "methods"      "base"        
## 
## [[9]]
##  [1] "rmarkdown"    "knitr"        "viridis"      "viridisLite"  "fst"         
##  [6] "RColorBrewer" "modelsummary" "effects"      "carData"      "lubridate"   
## [11] "forcats"      "stringr"      "dplyr"        "purrr"        "readr"       
## [16] "tidyr"        "tibble"       "ggplot2"      "tidyverse"    "stats"       
## [21] "graphics"     "grDevices"    "utils"        "datasets"     "methods"     
## [26] "base"        
## 
## [[10]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "fst"          "RColorBrewer" "modelsummary" "effects"      "carData"     
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[11]]
##  [1] "ggridges"     "rmarkdown"    "knitr"        "viridis"      "viridisLite" 
##  [6] "fst"          "RColorBrewer" "modelsummary" "effects"      "carData"     
## [11] "lubridate"    "forcats"      "stringr"      "dplyr"        "purrr"       
## [16] "readr"        "tidyr"        "tibble"       "ggplot2"      "tidyverse"   
## [21] "stats"        "graphics"     "grDevices"    "utils"        "datasets"    
## [26] "methods"      "base"        
## 
## [[12]]
##  [1] "questionr"    "ggridges"     "rmarkdown"    "knitr"        "viridis"     
##  [6] "viridisLite"  "fst"          "RColorBrewer" "modelsummary" "effects"     
## [11] "carData"      "lubridate"    "forcats"      "stringr"      "dplyr"       
## [16] "purrr"        "readr"        "tidyr"        "tibble"       "ggplot2"     
## [21] "tidyverse"    "stats"        "graphics"     "grDevices"    "utils"       
## [26] "datasets"     "methods"      "base"        
## 
## [[13]]
##  [1] "flextable"    "questionr"    "ggridges"     "rmarkdown"    "knitr"       
##  [6] "viridis"      "viridisLite"  "fst"          "RColorBrewer" "modelsummary"
## [11] "effects"      "carData"      "lubridate"    "forcats"      "stringr"     
## [16] "dplyr"        "purrr"        "readr"        "tidyr"        "tibble"      
## [21] "ggplot2"      "tidyverse"    "stats"        "graphics"     "grDevices"   
## [26] "utils"        "datasets"     "methods"      "base"        
## 
## [[14]]
##  [1] "infer"        "flextable"    "questionr"    "ggridges"     "rmarkdown"   
##  [6] "knitr"        "viridis"      "viridisLite"  "fst"          "RColorBrewer"
## [11] "modelsummary" "effects"      "carData"      "lubridate"    "forcats"     
## [16] "stringr"      "dplyr"        "purrr"        "readr"        "tidyr"       
## [21] "tibble"       "ggplot2"      "tidyverse"    "stats"        "graphics"    
## [26] "grDevices"    "utils"        "datasets"     "methods"      "base"
# Loading dataset
ess <- read_fst("All-ESS-Data.fst")

Cleaning variables for Part C) Context

# Initial cleaning of variables before going with the next way
sweden_data <- ess |>
  filter(cntry == "SE") |>
  mutate(happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
  lrscale = ifelse(lrscale %in% c(77, 88, 99), NA, lrscale),
  marsts = ifelse(marsts %in% c(66, 77, 88, 99), NA, marsts),
  hinctnta = ifelse(hinctnta %in% c(77, 88, 99), NA, hinctnta)
  )

# Filtering for country and cleaning variables
sweden_data <- sweden_data |>
  mutate(
  pol = 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(pol))
sweden_data <- sweden_data %>% filter(!is.nan(pol))
sweden_data <- sweden_data %>% filter(!is.infinite(pol))
unique(sweden_data$pol)
## [1] "Right"    "Moderate" "Left"
table(sweden_data$pol)
## 
##     Left Moderate    Right 
##     4362     7471     5641
sweden_data <- sweden_data %>% filter(!is.na(happy))

# Troubleshooting code 
# sweden_data <- sweden_data %>% filter(!is.nan(happiness))
# sweden_data <- sweden_data %>% filter(!is.infinite(happiness))
unique(sweden_data$happy)
##  [1]  7  9  6 10  8  4  5  3  2  1  0
table(sweden_data$happy)
## 
##    0    1    2    3    4    5    6    7    8    9   10 
##   30   33  115  225  299  916 1130 3139 5725 3766 2042
sweden_data <- sweden_data %>% filter(!is.na(marriage))
unique(sweden_data$marriage)
## [1] "Not married/union dissolved"           
## [2] "Legally married/registered civil union"
sweden_data <- sweden_data %>% filter(!is.na(income))
unique(sweden_data$discrimination)
## [1] "Not marked" "Marked"
# Troubleshooting
min(sweden_data$happy)
## [1] 0
max(sweden_data$happy)
## [1] 10
min(sweden_data$pol)
## [1] "Left"
max(sweden_data$pol)
## [1] "Right"
# Converting factors/characters to numeric 
sweden_data <- sweden_data |>
  mutate(
    happy_num = as.numeric(factor(happy)),
    pol_num = as.numeric(factor(pol, 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, pol_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

11

0

8.6

1.6

1.0

9.0

11.0

pol_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` = pol_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

11

0

8.6

1.6

1.0

9.0

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

Infer package four steps for Part D) Findings

# Step 1: Calculating test statistic
test_stat <- sweden_data |>
  specify(explanatory = pol, 
          response = happy) |> 
  hypothesize(null = "independence") |>
  calculate(stat = "F") 
print(test_stat$stat)
## [1] 27.25254
# Step 2: Simulating null distribution 
null_distribution <- sweden_data |>
  specify(explanatory = pol,
          response = happy) |>
  hypothesize(null = "independence") |>
  generate(reps = 1000, type = "permute") |>
  calculate(stat = "F")

# 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: happy (numeric)
## Explanatory: pol (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1 0.267 
##  2         2 0.778 
##  3         3 1.22  
##  4         4 0.248 
##  5         5 4.26  
##  6         6 0.0463
##  7         7 1.56  
##  8         8 0.886 
##  9         9 0.167 
## 10        10 1.33  
## # ℹ 990 more rows

Regression modelling for Part D) Findings

# Specifying single, multivariate, and interaction models 
sweden_data$weight <- sweden_data$dweight * sweden_data$pweight
model1 <- lm(happy ~ pol, data = sweden_data, weights = weight)
model2 <- lm(happy ~ pol + discrimination, data = sweden_data, weights = weight)
model3 <- lm(happy ~ pol + discrimination + income*marriage, data = sweden_data, weights = weight)

# Displaying coefficients for single model 
coefficients <- coef(model1)
print(coefficients)
## (Intercept) polModerate    polRight 
##   7.3693308   0.1988699   0.4855085
# Can't know number of observations until the following code works 
modelsummary(
  list(model1, model2, model3),
  fmt = 1,
  estimate  = c( "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}",
                "{estimate} ({std.error}){stars}"),
  statistic = NULL,
  coef_omit = "Intercept")
 (1)   (2)   (3)
polModerate 0.2 (0.1)** 0.2 (0.1)** 0.2 (0.1)*
polRight 0.5 (0.1)*** 0.5 (0.1)*** 0.4 (0.1)***
discriminationNot marked 0.0 (0.3) 0.0 (0.3)
incomeLow 1.2 (0.4)**
incomeMiddle 0.7 (0.4)+
marriageNot married/union dissolved 0.1 (0.3)
incomeLow × marriageNot married/union dissolved −0.4 (0.4)
incomeMiddle × marriageNot married/union dissolved −0.2 (0.4)
Num.Obs. 3921 3921 3921
R2 0.013 0.013 0.041
R2 Adj. 0.013 0.012 0.039
AIC 14853.0 14855.0 14754.9
BIC 14878.1 14886.4 14817.6
Log.Lik. −7422.502 −7422.494 −7367.443
RMSE 1.60 1.60 1.58
# Looking into robust standard errors
models <- list(
  "Model 1" = lm(happy ~ pol, data = sweden_data, weights = weight),
  "Model 2" = lm(happy ~ pol + discrimination, data = sweden_data, weights = weight),
  "Model 3" = lm(happy ~ pol + discrimination + income*marriage, data = sweden_data, weights = weight)
)

modelsummary(models)
Model 1  Model 2  Model 3
(Intercept) 7.369 7.406 6.880
(0.050) (0.302) (0.447)
polModerate 0.199 0.199 0.155
(0.064) (0.064) (0.063)
polRight 0.486 0.486 0.392
(0.068) (0.068) (0.068)
discriminationNot marked −0.037 0.034
(0.301) (0.297)
incomeLow 1.198
(0.418)
incomeMiddle 0.718
(0.371)
marriageNot married/union dissolved 0.056
(0.337)
incomeLow × marriageNot married/union dissolved −0.434
(0.426)
incomeMiddle × marriageNot married/union dissolved −0.210
(0.376)
Num.Obs. 3921 3921 3921
R2 0.013 0.013 0.041
R2 Adj. 0.013 0.012 0.039
AIC 14853.0 14855.0 14754.9
BIC 14878.1 14886.4 14817.6
Log.Lik. −7422.502 −7422.494 −7367.443
RMSE 1.60 1.60 1.58
modelsummary(models, vcov = "robust")
Model 1  Model 2  Model 3
(Intercept) 7.369 7.406 6.880
(0.055) (0.324) (0.605)
polModerate 0.199 0.199 0.155
(0.067) (0.068) (0.067)
polRight 0.486 0.486 0.392
(0.070) (0.070) (0.070)
discriminationNot marked −0.037 0.034
(0.325) (0.311)
incomeLow 1.198
(0.564)
incomeMiddle 0.718
(0.546)
marriageNot married/union dissolved 0.056
(0.523)
incomeLow × marriageNot married/union dissolved −0.434
(0.570)
incomeMiddle × marriageNot married/union dissolved −0.210
(0.551)
Num.Obs. 3921 3921 3921
R2 0.013 0.013 0.041
R2 Adj. 0.013 0.012 0.039
AIC 14853.0 14855.0 14754.9
BIC 14878.1 14886.4 14817.6
Log.Lik. −7422.502 −7422.494 −7367.443
RMSE 1.60 1.60 1.58
Std.Errors HC3 HC3 HC3