Setting up working directory and environment

# I used this any time I wanted to run anything from the beginning with a blank slate
rm(list=ls()); gc()
##          used (Mb) gc trigger (Mb) limit (Mb) max used (Mb)
## Ncells 522779 28.0    1158944 61.9         NA   669420 35.8
## Vcells 964273  7.4    8388608 64.0      16384  1851675 14.2
# Setting my working directory 
setwd("~/Desktop/SOC202")

# Loading all of the packages I used 
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")

# Note to self: All output must also be submitted as separate PDFs (Word also accepted) that we can individually open

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),
  hinctnta = ifelse(hinctnta %in% c(77, 88, 99), NA, hinctnta)
  )

# No longer using the variable: marsts = ifelse(marsts %in% c(66, 77, 88, 99), NA, marsts), sweden_data <- sweden_data %>% filter(!is.na(marriage)), unique(sweden_data$marriage), unique(sweden_data$discrimination)

# 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_      
    ),
  income = case_when(
      hinctnta %in% 1:2 ~ "High",                    
      hinctnta %in% 3:8 ~ "Middle",
      hinctnta %in% 9:10 ~ "Low",  
      hinctnta %in% c(77, 88, 99) ~ NA_character_      
  ))

# No longer using the following variables
# discrimination = recode(dscrrce, '0' = 'Not marked', '1' = 'Marked')
# 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_                

# 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))
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(income))

# Troubleshooting code 
# sweden_data <- sweden_data %>% filter(!is.nan(happiness))
# sweden_data <- sweden_data %>% filter(!is.infinite(happiness))

# 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"))),
    income_num = as.numeric(factor(income, levels = c("High", "Middle", "Low"))),
  )

# No longer using the following code:     marriage_num = as.numeric(factor(marriage, levels = c("Legally married/registered civil union", "Not married/union dissolved"))), discrimination_num = as.numeric(dscrrce)

# Producing first summary table
summary_table <- datasummary_skim(sweden_data %>% select(happy_num, pol_num, income_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.7

1.6

1.0

9.0

11.0

pol_num

3

0

2.1

0.8

1.0

2.0

3.0

income_num

3

0

2.2

0.6

1.0

2.0

3.0

# Saving summary table as word doc 
flextable::save_as_docx(summary_table, path = "summary_table.docx",
                       width = 7.0, height = 7.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`, `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.1

0.8

1.0

2.0

3.0

Reported levels of happiness

11

0

8.7

1.6

1.0

9.0

11.0

Household's total net income

3

0

2.2

0.6

1.0

2.0

3.0

# Saving summary table as word doc 
flextable::save_as_docx(Sweden_summary_table, path = "Sweden_summary_table.docx",
                       width = 7.0, height = 7.0)

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


Sweden_summary_table_2
Table 2. Categorical Predictors Summary

N

%

pol

Left

2824

25.1

Moderate

4685

41.7

Right

3729

33.2

income

High

1384

12.3

Low

3136

27.9

Middle

6718

59.8

# Saving summary table as word doc 
flextable::save_as_docx(Sweden_summary_table_2, path = "Sweden_summary_table_2.docx",
                       width = 7.0, height = 7.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] 51.2859
# 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 |>
  assume(distribution = "F") |>
  visualize() +
  ggtitle("Figure 1. Theoretical F Null Distribution") +
  shade_p_value(test_stat,
                direction = "greater")

# Me attempting to save the visualization as a pdf
# ggsave("Figure 1. Theoretical F Null Distribution.pdf", device = "pdf", width = 6, height = 4)
# ggsave("Figure1_theoretical_f_null_distribution.pdf", device = "pdf")

null_distribution
## Response: happy (numeric)
## Explanatory: pol (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
##    replicate   stat
##        <int>  <dbl>
##  1         1 0.181 
##  2         2 2.86  
##  3         3 0.593 
##  4         4 0.443 
##  5         5 0.0576
##  6         6 0.405 
##  7         7 0.357 
##  8         8 0.593 
##  9         9 0.223 
## 10        10 0.260 
## # ℹ 990 more rows
# No longer using the following code for the poster
 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

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 + income, data = sweden_data, weights = weight)
model3 <- lm(happy ~ pol*income, data = sweden_data, weights = weight)

# No longer using the following models
# 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.5432893   0.2002419   0.4116484
# Creating list of models
# Make sure to give the model summary the title "Table 2. Summary of Regression Models"
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.0)*** 0.2 (0.0)*** 0.3 (0.1)**
polRight 0.4 (0.0)*** 0.3 (0.0)*** 0.5 (0.1)***
incomeLow 1.0 (0.1)*** 1.0 (0.1)***
incomeMiddle 0.7 (0.0)*** 0.8 (0.1)***
polModerate × incomeLow −0.1 (0.1)
polRight × incomeLow −0.1 (0.1)
polModerate × incomeMiddle −0.1 (0.1)
polRight × incomeMiddle −0.2 (0.1)
Num.Obs. 11238 11238 11238
R2 0.010 0.040 0.041
R2 Adj. 0.009 0.040 0.040
AIC 42469.4 42118.4 42122.5
BIC 42498.7 42162.4 42195.8
Log.Lik. −21230.712 −21053.221 −21051.267
RMSE 1.61 1.58 1.58
# Looking into robust standard errors
models <- list(
  "Model 1" = lm(happy ~ pol, data = sweden_data, weights = weight),
  "Model 2" = lm(happy ~ pol + income, data = sweden_data, weights = weight),
  "Model 3" = lm(happy ~ pol*income, data = sweden_data, weights = weight)
)

# Do not know how to save these as PDFs
modelsummary(models)
Model 1  Model 2  Model 3
(Intercept) 7.543 6.920 6.838
(0.030) (0.048) (0.074)
polModerate 0.200 0.168 0.283
(0.038) (0.037) (0.098)
polRight 0.412 0.326 0.459
(0.040) (0.040) (0.111)
incomeLow 0.963 1.025
(0.051) (0.097)
incomeMiddle 0.664 0.776
(0.046) (0.083)
polModerate × incomeLow −0.116
(0.125)
polRight × incomeLow −0.084
(0.134)
polModerate × incomeMiddle −0.142
(0.109)
polRight × incomeMiddle −0.190
(0.122)
Num.Obs. 11238 11238 11238
R2 0.010 0.040 0.041
R2 Adj. 0.009 0.040 0.040
AIC 42469.4 42118.4 42122.5
BIC 42498.7 42162.4 42195.8
Log.Lik. −21230.712 −21053.221 −21051.267
RMSE 1.61 1.58 1.58
modelsummary(models, vcov = "robust")
Model 1  Model 2  Model 3
(Intercept) 7.543 6.920 6.838
(0.033) (0.059) (0.096)
polModerate 0.200 0.168 0.283
(0.040) (0.039) (0.125)
polRight 0.412 0.326 0.459
(0.041) (0.041) (0.141)
incomeLow 0.963 1.025
(0.058) (0.113)
incomeMiddle 0.664 0.776
(0.056) (0.104)
polModerate × incomeLow −0.116
(0.143)
polRight × incomeLow −0.084
(0.156)
polModerate × incomeMiddle −0.142
(0.135)
polRight × incomeMiddle −0.190
(0.150)
Num.Obs. 11238 11238 11238
R2 0.010 0.040 0.041
R2 Adj. 0.009 0.040 0.040
AIC 42469.4 42118.4 42122.5
BIC 42498.7 42162.4 42195.8
Log.Lik. −21230.712 −21053.221 −21051.267
RMSE 1.61 1.58 1.58
Std.Errors HC3 HC3 HC3

Visual of choice for Part D) Findings

# This code isn't needed
ess$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
  ess$year[ess$essround == i] <- replacements[i]
}

# Possible visual, copied from tutorial, showing model 3
interaction_plot <- effect("pol*income", model3, na.rm=TRUE)

plot(interaction_plot,
     main="Figure 3. Interaction effect of political placement and income levels",
     xlab="Household's total net income",
     ylab="Reported level's of happiness")

# Trying and failing to save interaction plot as a PDF
# ggsave("InteractionPlot.pdf", plot = interaction_plot, width = 6, height = 4)
# ggsave(filename = "InteractionPlot.pdf", plot = interaction_plot, device = "pdf", width = 6, height = 4)

# Trying out the following code
# multivariate_plot <- effect("income", model2, xlevels = list(pol = unique(sweden_data$pol)), data = sweden_data, weights = sweden_data$weight)
# The above accomplishes the same thing as below

# Possible visual showing model 2
multivariate_plot <- effect("income", model2, na.rm=TRUE)

plot(multivariate_plot,
     main = "Multivariate model",
     xlab="Household's total net income",
     ylab= "Reported level's of happiness")

# Possible visual showing model 1 
single_plot <- effect("pol", model1, na.rm=TRUE)

plot(single_plot,
     main = "Figure 2. Single model of political placement and happiness",
     xlab="Political placement",
     ylab= "Reported level's of happiness")