# List of packages
packages <- c("tidyverse", "infer", "fst", "modelsummary", "effects", "survey", "MASS", "kableExtra", "flextable", "equatiomatic")
# Install packages if they aren't installed already
new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)
# Load the 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: grid
##
## Loading required package: Matrix
##
##
## Attaching package: 'Matrix'
##
##
## The following objects are masked from 'package:tidyr':
##
## expand, pack, unpack
##
##
## Loading required package: survival
##
##
## Attaching package: 'survey'
##
##
## The following object is masked from 'package:graphics':
##
## dotchart
##
##
##
## Attaching package: 'MASS'
##
##
## The following object is masked from 'package:dplyr':
##
## select
##
##
##
## Attaching package: 'kableExtra'
##
##
## The following object is masked from 'package:dplyr':
##
## group_rows
##
##
##
## Attaching package: 'flextable'
##
##
## The following objects are masked from 'package:kableExtra':
##
## as_image, footnote
##
##
## 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] "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"
##
## [[4]]
## [1] "modelsummary" "fst" "infer" "lubridate" "forcats"
## [6] "stringr" "dplyr" "purrr" "readr" "tidyr"
## [11] "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [16] "grDevices" "utils" "datasets" "methods" "base"
##
## [[5]]
## [1] "effects" "carData" "modelsummary" "fst" "infer"
## [6] "lubridate" "forcats" "stringr" "dplyr" "purrr"
## [11] "readr" "tidyr" "tibble" "ggplot2" "tidyverse"
## [16] "stats" "graphics" "grDevices" "utils" "datasets"
## [21] "methods" "base"
##
## [[6]]
## [1] "survey" "survival" "Matrix" "grid" "effects"
## [6] "carData" "modelsummary" "fst" "infer" "lubridate"
## [11] "forcats" "stringr" "dplyr" "purrr" "readr"
## [16] "tidyr" "tibble" "ggplot2" "tidyverse" "stats"
## [21] "graphics" "grDevices" "utils" "datasets" "methods"
## [26] "base"
##
## [[7]]
## [1] "MASS" "survey" "survival" "Matrix" "grid"
## [6] "effects" "carData" "modelsummary" "fst" "infer"
## [11] "lubridate" "forcats" "stringr" "dplyr" "purrr"
## [16] "readr" "tidyr" "tibble" "ggplot2" "tidyverse"
## [21] "stats" "graphics" "grDevices" "utils" "datasets"
## [26] "methods" "base"
##
## [[8]]
## [1] "kableExtra" "MASS" "survey" "survival" "Matrix"
## [6] "grid" "effects" "carData" "modelsummary" "fst"
## [11] "infer" "lubridate" "forcats" "stringr" "dplyr"
## [16] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [21] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [26] "datasets" "methods" "base"
##
## [[9]]
## [1] "flextable" "kableExtra" "MASS" "survey" "survival"
## [6] "Matrix" "grid" "effects" "carData" "modelsummary"
## [11] "fst" "infer" "lubridate" "forcats" "stringr"
## [16] "dplyr" "purrr" "readr" "tidyr" "tibble"
## [21] "ggplot2" "tidyverse" "stats" "graphics" "grDevices"
## [26] "utils" "datasets" "methods" "base"
##
## [[10]]
## [1] "equatiomatic" "flextable" "kableExtra" "MASS" "survey"
## [6] "survival" "Matrix" "grid" "effects" "carData"
## [11] "modelsummary" "fst" "infer" "lubridate" "forcats"
## [16] "stringr" "dplyr" "purrr" "readr" "tidyr"
## [21] "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [26] "grDevices" "utils" "datasets" "methods" "base"
# Load ESS file
ess <- read_fst("~/Documents/__School/2324 UofT/SOC202/R/All-ESS-Data.fst")
denmark_data <- ess %>%
filter(cntry == "DK")
df <- denmark_data
denmark_clean <- denmark_data %>%
mutate(
# Filtering out NA in the happy variable
happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
# Filtering out NA in the happy variable
stfgov = ifelse(stfgov %in% c(77, 88, 99), NA, stfgov),
# Recoding the blgetmg variable (ethnic minority or not)
minority = case_when(
blgetmg %in% c(7, 8, 9) ~ NA_character_,
blgetmg == 1 ~ "Ethnic Minority",
blgetmg == 2 ~ "Not Ethnic Minority",
TRUE ~ as.character(blgetmg)),
) %>%
filter(!is.na(happy) & !is.na(minority) & !is.na(stfgov))
# Checking to make sure NA values are filtered out
table(denmark_clean$minority)
##
## Ethnic Minority Not Ethnic Minority
## 331 11690
table(denmark_clean$happy)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 11 23 39 75 97 324 393 1315 3741 3674 2329
table(denmark_clean$stfgov)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 414 378 727 1271 1323 1871 1664 1963 1682 513 215
denmark_data$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
denmark_data$year[denmark_data$essround == i] <- replacements[i]}
# Filter out data
denmark_df <- denmark_data %>%
mutate(
happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
stfgov = ifelse(stfgov %in% c(77, 88, 99), NA, stfgov),
minority = ifelse(blgetmg %in% c(7, 8, 9), NA, blgetmg)
)
# Rename variable names for legibility in poster
denmark_df <- denmark_df %>%
rename(
`Happiness` = happy,
`Satisfaction with Government` = stfgov,
`Ethnic Minority` = minority
)
# Create Data Summary Table
t1 <- datasummary_skim(denmark_df
%>% dplyr::select(`Happiness`, `Satisfaction with Government`, `Ethnic Minority`), output = "flextable",
title = "Table 1: Descriptive Statistics for Variables of Interest")
## 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.
t1
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max |
|---|---|---|---|---|---|---|---|
Happiness | 12 | 1 | 8.3 | 1.4 | 0.0 | 8.0 | 10.0 |
Satisfaction with Government | 12 | 2 | 5.3 | 2.3 | 0.0 | 6.0 | 10.0 |
Ethnic Minority | 3 | 0 | 2.0 | 0.2 | 1.0 | 2.0 | 2.0 |
We use a t-test because the explanatory variable (minority) has two categories and the response variable (happy) is numeric
# Calculate test statistic
test_stat <- denmark_clean %>%
specify(explanatory = minority, response = happy) %>%
hypothesize(null = "independence") %>%
calculate(stat = "t")
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "Ethnic Minority" - "Not Ethnic Minority", or divided in the order
## "Ethnic Minority" / "Not Ethnic Minority" for ratio-based statistics. To
## specify this order yourself, supply `order = c("Ethnic Minority", "Not Ethnic
## Minority")` to the calculate() function.
print(test_stat$stat)
## t
## -3.906932
# Simulate null distribution
null_distribution <- denmark_clean %>%
specify(explanatory = minority, response = happy) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "t")
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "Ethnic Minority" - "Not Ethnic Minority", or divided in the order
## "Ethnic Minority" / "Not Ethnic Minority" for ratio-based statistics. To
## specify this order yourself, supply `order = c("Ethnic Minority", "Not Ethnic
## Minority")` to the calculate() function.
null_distribution
## Response: happy (numeric)
## Explanatory: minority (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 -0.0958
## 2 2 0.425
## 3 3 0.247
## 4 4 0.0586
## 5 5 1.49
## 6 6 -0.809
## 7 7 -0.857
## 8 8 0.697
## 9 9 -0.556
## 10 10 -0.814
## # ℹ 990 more rows
# Find p-value
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
# Visualize the distribution
conf_int <- null_distribution %>%
get_confidence_interval(level = 0.95, type = "percentile")
p1 <- null_distribution %>%
visualize(data, bins = 10, method = "simulation", dens_color = "black",
title = "Simulation-Based") +
shade_p_value(obs_stat = test_stat, direction = "two-sided") +
shade_confidence_interval(endpoints = conf_int) +
labs(title = "Figure 1. Simulation-Based Null Distribution for T-Distribution",
x = "Test Statistic", y = "Count")
p1
ggsave(filename = "plot1.pdf", plot = p1, device = "pdf", width = 6, height = 4)
denmark_clean$weight <- denmark_clean$dweight * denmark_clean$pweight
model1 <- lm(happy ~ minority, data = denmark_clean, weights = weight)
model2 <- lm(happy ~ minority + stfgov, data = denmark_clean, weights = weight)
model3 <- lm(happy ~ minority + stfgov*minority, data = denmark_clean, weights = weight)
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",
title = "Table 2. Comparing Regression Models' Fit Metrics")
| (1) | (2) | (3) | |
|---|---|---|---|
| minorityNot Ethnic Minority | 0.4 (0.1)*** | 0.4 (0.1)*** | 0.8 (0.2)*** |
| stfgov | 0.1 (0.0)*** | 0.2 (0.0)*** | |
| minorityNot Ethnic Minority × stfgov | −0.1 (0.0)** | ||
| Num.Obs. | 12021 | 12021 | 12021 |
| R2 | 0.002 | 0.029 | 0.030 |
| R2 Adj. | 0.002 | 0.029 | 0.029 |
| AIC | 42482.5 | 42155.8 | 42150.1 |
| BIC | 42504.7 | 42185.3 | 42187.1 |
| Log.Lik. | −21238.246 | −21073.877 | −21070.053 |
| F | 26.170 | 180.042 | 122.644 |
| RMSE | 1.41 | 1.40 | 1.40 |
p2 <- denmark_clean %>%
ggplot(aes(x = minority, y = happy, fill = minority)) +
geom_boxplot() +
labs(x = "Minority", y = "Happiness Levels (0-10)", title = "Figure 2. Happiness Levels Between Ethnic Minorities \nand Non-Ethnic Minorities in Denmark") +
theme_minimal()
ggsave(filename = "plot2.pdf", plot = p2, device = "pdf", width = 6, height = 4)