rm(list=ls()); gc()
## used (Mb) gc trigger (Mb) limit (Mb) max used (Mb)
## Ncells 522719 28.0 1158772 61.9 NA 669420 35.8
## Vcells 963717 7.4 8388608 64.0 16384 1851675 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")
# 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% 9:10 ~ "Low",
hinctnta %in% 3:8 ~ "Middle",
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))
# 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(income))
# 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 |
# 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 |
# 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 1. Categorical Predictors Summary", output = "flextable")
Sweden_summary_table_2
|
| 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 |
# Saves as PDF (DONT RUN UNTIL END)
# set_flextable_defaults(fonts_ignore=TRUE)
# print(summary_table_v2, preview = "pdf")
# 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() +
shade_p_value(test_stat,
direction = "greater")
null_distribution
## Response: happy (numeric)
## Explanatory: pol (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.959
## 2 2 0.0874
## 3 3 0.567
## 4 4 9.96
## 5 5 0.718
## 6 6 0.618
## 7 7 0.485
## 8 8 1.77
## 9 9 4.57
## 10 10 0.110
## # ℹ 990 more rows
# No longer using the following code
# null_distribution |>
# visualize() +
# shade_p_value(obs_stat = test_stat, direction = "greater")
# 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
# 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.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)
)
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 |
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
interaction_plot <- effect("pol*income", model3, na.rm=TRUE)
plot(interaction_plot,
main="Interaction effect",
xlab="Household's total net income",
ylab="Political placement")