# List of packages
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer",
"fst", "viridis", "knitr", "kableExtra", "rmarkdown", "ggridges", "viridis", "questionr")
# 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.4 ✔ 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: 'kableExtra'
##
##
## The following object is masked from 'package:dplyr':
##
## group_rows
## [[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] "kableExtra" "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] "rmarkdown" "kableExtra" "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" "kableExtra" "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"
##
## [[11]]
## [1] "ggridges" "rmarkdown" "kableExtra" "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] "questionr" "ggridges" "rmarkdown" "kableExtra" "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"
ess <- read_fst("All-ESS-Data.fst")
denmark_data <- ess %>%
filter(cntry == "DK")
write_fst(denmark_data, "/Users/Yixuan/Desktop/SOC202/All-ESS-Data.fst ")
df <- read_fst("/Users/Yixuan/Desktop/SOC202/All-ESS-Data.fst ")
df$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
df$year[df$essround == i] <- replacements[i]
}
denmark_data <- df
# Do getwd() to check
getwd()
## [1] "/Users/Yixuan/Desktop/SOC202"
denmark_data_table_subset <- denmark_data %>%
mutate(
evmar = ifelse(evmar == 2, 0, ifelse(evmar %in% c(7, 8, 9), NA, evmar)),
health = ifelse(health %in% c(77, 88, 99), NA, health),
stflife = ifelse(stflife %in% c(77, 88, 99), NA, stflife)
)
summary_table <- datasummary_skim(denmark_data_table_subset %>% select(evmar, health, stflife), 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 |
|---|---|---|---|---|---|---|---|
evmar | 3 | 75 | 0.7 | 0.5 | 0.0 | 1.0 | 1.0 |
health | 7 | 0 | 1.9 | 1.0 | 1.0 | 2.0 | 9.0 |
stflife | 12 | 0 | 8.5 | 1.5 | 0.0 | 9.0 | 10.0 |
denmark_data_v2 <- denmark_data_table_subset %>%
rename(
`Marital status` = evmar,
`Subjective general health` = health,
`Satisfaction with life as a whole` = stflife
)
summary_table_v2 <- datasummary_skim(denmark_data_v2 %>% select(`Marital status`,`Subjective general health`, `Satisfaction with life as a whole`), output = "flextable", title = "Table 1: Descriptive statistics of main variables")
## 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_v2
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max |
|---|---|---|---|---|---|---|---|
Marital status | 3 | 75 | 0.7 | 0.5 | 0.0 | 1.0 | 1.0 |
Subjective general health | 7 | 0 | 1.9 | 1.0 | 1.0 | 2.0 | 9.0 |
Satisfaction with life as a whole | 12 | 0 | 8.5 | 1.5 | 0.0 | 9.0 | 10.0 |
denmark_data <- ess %>%
filter(cntry == "DK") %>%
mutate(
evmar = case_when(
evmar == 1 ~ "Yes",
evmar == 2 ~ "No",
evmar %in% c(7, 9) ~ NA_character_,
TRUE ~ as.character(evmar)
),
stflife = case_when(
stflife %in% c("0", "1", "2", "3") ~ "Dissatisfied",
stflife %in% c("4", "5", "6") ~ "Moderate",
stflife %in% c("7", "8", "9", "10") ~ "Satisfied",
stflife %in% c(77, 88, 99) ~ NA_character_,
TRUE ~ as.character(stflife)
)
)
# Install or reinstall the infer package
options(repos = c(CRAN = "https://cran.rstudio.com"))
install.packages("infer")
##
## The downloaded binary packages are in
## /var/folders/_p/_g5dt2vs5mv9tfwjprtvtz6h0000gn/T//RtmpvFa0yK/downloaded_packages
# Load the infer package
library(infer)
# Step 1: Calculate the test statistic of your sample
test_stat <- denmark_data %>%
specify(explanatory = stflife, response = evmar) %>%
hypothesize(null = "independence") %>%
calculate(stat = "chisq")
## Warning: Removed 9358 rows containing missing values.
# Print the test statistic
print(test_stat$stat)
## X-squared
## 5.000714
# Step 2: Simulate the null distribution
null_distribution <- denmark_data %>%
specify(explanatory = stflife,
response = evmar) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "chisq")
## Warning: Removed 9358 rows containing missing values.
# Step 3: Calculate the p-value of your sample
p_val <- null_distribution %>%
get_pvalue(obs_stat = test_stat, direction = "two-sided")
# Step 4: Visualize
# Visualize with confidence intervals
conf_int <- null_distribution %>%
get_confidence_interval(level = 0.95, type = "percentile")
# Plot
null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided") +
shade_confidence_interval(endpoints = conf_int) +
ggtitle("Figure 1. Simulation-Based Null Distribution")
## Warning: Chi-Square usually corresponds to right-tailed tests. Proceed with
## caution.
The P-value displaced as 0.178 unfortunately fails to reject the H0,
meaning that there are not enough evidence to reject the Null
Hypothesis, and the result is perhaps not statistically significant. The
Figure 1 is left skewed, and it might indicates to the non-normality of
the data. There are no strong proof to prove that our variables are
connected.
library(dplyr)
library(ggplot2)
# Process data
denmark_data <- ess
denmark_data_processed <- denmark_data %>%
mutate(
evmar = case_when(
evmar == 1 ~ 'Yes',
evmar == 2 ~ 'No',
TRUE ~ NA_character_
)
) %>%
filter(!is.na(evmar))
# Create the boxplot
ggplot(denmark_data_processed, aes(x = evmar, y = stflife, fill = evmar)) +
geom_boxplot() +
theme_minimal() +
labs(title = "Life Satisfaction by Marital Status in Denmark",
x = "Marital Status",
y = "Life Satisfaction Score") +
scale_fill_brewer(palette = "Set1") +
scale_y_continuous(limits = c(0, 10))
## Warning: Removed 508 rows containing non-finite values (`stat_boxplot()`).
The Figure 2 is a boxplot showcasing the comparison of life satisfaction
between people who are or have been married and never married in
Denmark.
We could perceive from the Figure 2 that people who have never married is less than people who are or have been married, with the median of the “yes” box merely equals to the Q3 value of the “no” box.
There are more lower outliers in the range of no than yes, meaning that people who have never married are more likely to feel extremely unsatisfied with their life in Denmark than those who are or once married.
# Subsetting to country
denmark_data <- ess %>%
filter(cntry == "DK")
df <- denmark_data
df <- df %>%
mutate(
stflife = ifelse(stflife %in% c(77, 88, 99), NA, stflife),
evmar = case_when(
evmar == 1 ~ 1, # Yes
evmar == 2 ~ 0, # No
evmar %in% c(7, 9) ~ NA_integer_,
TRUE ~ NA_integer_
),
health = ifelse(health %in% c(7, 8, 9), NA, health)
)
df$weight <- df$dweight * df$pweight
model1 <- lm(stflife ~ evmar, data = df, weights = weight)
model2 <- lm(stflife ~ health, data = df, weights = weight)
model3 <- lm(stflife ~ evmar + health, data = df, weights = weight)
# Display summaries
model_summaries <- modelsummary(list("Model 1" = model1, "Model 2" = model2, "Model 3" = model3),
fmt = 1,
estimate = c("{estimate} ({std.error}){stars}",
"{estimate} ({std.error}){stars}",
"{estimate} ({std.error}){stars}"),
statistic = NULL,
title = 'Table 2. Regression models of life satisfaction (scale 0 to 10)')
install.packages("effects")
##
## The downloaded binary packages are in
## /var/folders/_p/_g5dt2vs5mv9tfwjprtvtz6h0000gn/T//RtmpvFa0yK/downloaded_packages
library(effects)
## Loading required package: carData
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
interaction_plot <- effect("evmar*health", model3, na.rm=TRUE)
## NOTE: evmar:health does not appear in the model
plot(interaction_plot,
main="Interaction effect",
xlab="Marital Status",
ylab="Health")
# Print or display your model summaries
print(model_summaries)
## <table class="table" style="width: auto !important; margin-left: auto; margin-right: auto;">
## <caption>Table 2. Regression models of life satisfaction (scale 0 to 10)</caption>
## <thead>
## <tr>
## <th style="text-align:left;"> </th>
## <th style="text-align:center;"> Model 1 </th>
## <th style="text-align:center;"> Model 2 </th>
## <th style="text-align:center;"> Model 3 </th>
## </tr>
## </thead>
## <tbody>
## <tr>
## <td style="text-align:left;"> (Intercept) </td>
## <td style="text-align:center;"> 8.3 (0.0)*** </td>
## <td style="text-align:center;"> 9.4 (0.0)*** </td>
## <td style="text-align:center;"> 9.1 (0.1)*** </td>
## </tr>
## <tr>
## <td style="text-align:left;"> evmar </td>
## <td style="text-align:center;"> 0.3 (0.1)*** </td>
## <td style="text-align:center;"> </td>
## <td style="text-align:center;"> 0.4 (0.1)*** </td>
## </tr>
## <tr>
## <td style="text-align:left;box-shadow: 0px 1.5px"> health </td>
## <td style="text-align:center;box-shadow: 0px 1.5px"> </td>
## <td style="text-align:center;box-shadow: 0px 1.5px"> −0.5 (0.0)*** </td>
## <td style="text-align:center;box-shadow: 0px 1.5px"> −0.5 (0.0)*** </td>
## </tr>
## <tr>
## <td style="text-align:left;"> Num.Obs. </td>
## <td style="text-align:center;"> 3050 </td>
## <td style="text-align:center;"> 12350 </td>
## <td style="text-align:center;"> 3046 </td>
## </tr>
## <tr>
## <td style="text-align:left;"> R2 </td>
## <td style="text-align:center;"> 0.011 </td>
## <td style="text-align:center;"> 0.081 </td>
## <td style="text-align:center;"> 0.096 </td>
## </tr>
## <tr>
## <td style="text-align:left;"> R2 Adj. </td>
## <td style="text-align:center;"> 0.011 </td>
## <td style="text-align:center;"> 0.081 </td>
## <td style="text-align:center;"> 0.095 </td>
## </tr>
## <tr>
## <td style="text-align:left;"> AIC </td>
## <td style="text-align:center;"> 11035.0 </td>
## <td style="text-align:center;"> 44325.4 </td>
## <td style="text-align:center;"> 10753.1 </td>
## </tr>
## <tr>
## <td style="text-align:left;"> BIC </td>
## <td style="text-align:center;"> 11053.1 </td>
## <td style="text-align:center;"> 44347.7 </td>
## <td style="text-align:center;"> 10777.2 </td>
## </tr>
## <tr>
## <td style="text-align:left;"> Log.Lik. </td>
## <td style="text-align:center;"> −5514.502 </td>
## <td style="text-align:center;"> −22159.710 </td>
## <td style="text-align:center;"> −5372.575 </td>
## </tr>
## <tr>
## <td style="text-align:left;"> RMSE </td>
## <td style="text-align:center;"> 1.48 </td>
## <td style="text-align:center;"> 1.45 </td>
## <td style="text-align:center;"> 1.41 </td>
## </tr>
## </tbody>
## </table>
The AIC of the three models are separately 11035.0, 44325.4, and 10753.1. Since the smaller the AIC the better fitting model, the model 3 of health is the best fitting among all three.
The models seems to have reasonable values of fitness, however we failed to reject the Null Hypothesis at the very first of the research, and thus, our variables may be otherly significant but do not have statistically significance.