packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer",
"fst", "viridis", "knitr", "kableExtra", "rmarkdown", "ggridges", "viridis", "questionr", "infer", "broom")
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.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"
##
## [[13]]
## [1] "infer" "questionr" "ggridges" "rmarkdown" "kableExtra"
## [6] "knitr" "viridis" "viridisLite" "fst" "RColorBrewer"
## [11] "modelsummary" "lubridate" "forcats" "stringr" "dplyr"
## [16] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [21] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [26] "datasets" "methods" "base"
##
## [[14]]
## [1] "broom" "infer" "questionr" "ggridges" "rmarkdown"
## [6] "kableExtra" "knitr" "viridis" "viridisLite" "fst"
## [11] "RColorBrewer" "modelsummary" "lubridate" "forcats" "stringr"
## [16] "dplyr" "purrr" "readr" "tidyr" "tibble"
## [21] "ggplot2" "tidyverse" "stats" "graphics" "grDevices"
## [26] "utils" "datasets" "methods" "base"
ess <- read_fst("All-ESS-Data.fst")
context
france_data <- ess %>%
filter(cntry == "FR")
write_fst(france_data, "/Users/sss/Desktop/soc202 poster/france_data.fst")
rm(list=ls()); gc()
## used (Mb) gc trigger (Mb) limit (Mb) max used (Mb)
## Ncells 1274546 68.1 2132121 113.9 NA 2132121 113.9
## Vcells 2169868 16.6 1257041696 9590.5 16384 1355995208 10345.5
df <- read_fst("/Users/sss/Desktop/Chai_Ruoci_Project_202/france_data.fst")
df$year <- NA
# Create a vector 'replacements' containing specific years.
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
df$year[df$essround == i] <- replacements[i]
}
france_data <- df
france_data_table_subset <- france_data %>%
mutate(
stfgov = ifelse(stfgov %in% c(77, 88, 99), NA, stfgov),
edulvla = ifelse(edulvla %in% c(55, 77, 88, 99), NA, edulvla),
domicil = ifelse(domicil %in% c(7, 8, 9), NA, domicil),
)
#exclude meaningless data
datasummary_skim(france_data %>% select(stfgov, edulvla, domicil))
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max | ||
|---|---|---|---|---|---|---|---|---|
| stfgov | 13 | 0 | 5.0 | 10.2 | 0.0 | 4.0 | 88.0 | |
| edulvla | 8 | 61 | 3.1 | 2.7 | 1.0 | 3.0 | 88.0 | |
| domicil | 7 | 0 | 2.9 | 1.2 | 1.0 | 3.0 | 8.0 |
france_data <- france_data_table_subset %>%
rename(
`How satisfied with the national government` = stfgov,
`highest level of education` = edulvla,
`domicile` = domicil
)
summary_table <- datasummary_skim(france_data %>% select(`How satisfied with the national government`,`highest level of education`, `domicile`), output = "flextable", title = "Table 1: Descriptive Statistics for 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
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max |
|---|---|---|---|---|---|---|---|
How satisfied with the national government | 12 | 1 | 3.7 | 2.3 | 0.0 | 4.0 | 10.0 |
highest level of education | 6 | 61 | 3.0 | 1.4 | 1.0 | 3.0 | 5.0 |
domicile | 6 | 0 | 2.9 | 1.2 | 1.0 | 3.0 | 5.0 |
##findings
france_data <- france_data %>%
mutate(
`highest level of education` = case_when(
essround < 5 & `highest level of education` == 55 ~ NA_real_,
TRUE ~ `highest level of education`
),
edulvlb = case_when(
essround >= 5 & edulvlb == 5555 ~ NA_real_,
TRUE ~ edulvlb
),
educ_level = case_when(
essround < 5 & `highest level of education` == 5 ~ "BA",
essround >= 5 & edulvlb > 600 ~ "BA",
TRUE ~ "No BA"
)
)
#add edulvlb data set and recode them into "No BA" and "BA"
table(france_data$educ_level)
##
## BA No BA
## 4235 14803
table(france_data$`How satisfied with the national government`)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 2131 1241 2381 2823 2640 3538 1843 1275 650 134 102
table(france_data$`domicile`)
##
## 1 2 3 4 5
## 3584 2361 6257 5668 1162
# Step 1: Calculate the test statistic
test_stat <- france_data %>%
specify(explanatory = educ_level,
response = `How satisfied with the national government`) %>%
hypothesize(null = "independence") %>%
calculate(stat = "t")
## Warning: Removed 280 rows containing missing values.
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "BA" - "No BA", or divided in the order "BA" / "No BA" for ratio-based
## statistics. To specify this order yourself, supply `order = c("BA", "No BA")`
## to the calculate() function.
print(test_stat$stat)
## t
## 9.370928
# Step 2: Simulate the null distribution
null_distribution <- france_data %>%
specify(explanatory = educ_level,
response = `How satisfied with the national government`) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "t")
## Warning: Removed 280 rows containing missing values.
## Warning: The statistic is based on a difference or ratio; by default, for
## difference-based statistics, the explanatory variable is subtracted in the
## order "BA" - "No BA", or divided in the order "BA" / "No BA" for ratio-based
## statistics. To specify this order yourself, supply `order = c("BA", "No BA")`
## to the calculate() function.
# Step 3: Calculate the p-value of your sample
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
it’s essentially a p-value of 0, not 0 – but, still, under the assumptions of frequentist hypothesis testing, this means there is strong evidence to reject the null.
#visualize
null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided")
labs(title = "Plot 1: Null Distribution")
## $title
## [1] "Plot 1: Null Distribution"
##
## attr(,"class")
## [1] "labels"
null_distribution
## Response: How satisfied with the national government (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 1.45
## 2 2 1.26
## 3 3 -0.620
## 4 4 0.489
## 5 5 0.103
## 6 6 -0.290
## 7 7 -1.38
## 8 8 -1.58
## 9 9 -1.23
## 10 10 -1.16
## # ℹ 990 more rows
#add confidence interval
conf_int <- null_distribution %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided") +
shade_confidence_interval(endpoints = conf_int)
null_distribution
## Response: How satisfied with the national government (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 1.45
## 2 2 1.26
## 3 3 -0.620
## 4 4 0.489
## 5 5 0.103
## 6 6 -0.290
## 7 7 -1.38
## 8 8 -1.58
## 9 9 -1.23
## 10 10 -1.16
## # ℹ 990 more rows
test statistic is 9.370928. In the graph, this is the value where the red line is drawn.
the p-value is 0, which indicates that the probability of observing a test statistic as extreme as 9.370928 under the null hypothesis is extremely low.
The red line (test statistic) falls far to the right of the simulated null distribution, indicating that your observed statistic is quite extreme compared to what we would expect if the null hypothesis were true.
A p-value of 0 (or a value extremely close to 0) is less than significance level I can reject the null hypothesis with a high degree of confidence.
#modelling
#create model1 that explains how education level influences satisfaction with the national government.
model1 <- lm(`How satisfied with the national government` ~ educ_level, data = france_data, weights = weight)
modelsummary(
list(model1),
fmt = 1,
estimate = c( "{estimate} ({std.error}){stars}"),
statistic = NULL,
coef_omit = "Intercept")
| Â (1) | |
|---|---|
| educ_levelNo BA | −0.4 (0.1)*** |
| Num.Obs. | 1893 |
| R2 | 0.007 |
| R2 Adj. | 0.006 |
| AIC | 8507.5 |
| BIC | 8524.1 |
| Log.Lik. | −4250.728 |
| RMSE | 2.07 |
france_data <- france_data %>%
mutate(geo = recode(as.character(`domicile`),
'1' = "Urban",
'2' = "Urban",
'3' = "Rural",
'4' = "Rural",
'5' = "Rural",
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_))
table(france_data$domicil)
##
## 1 2 3 4 5
## 3584 2361 6257 5668 1162
#recode domicile
#create model2 that adds domicile as another explanatory variable alongside education level
model2 <- lm(`How satisfied with the national government` ~ `domicile` + educ_level, data = france_data, weights = weight)
modelsummary(
list(model1, model2),
fmt = 1,
estimate = c( "{estimate} ({std.error}){stars}",
"{estimate} ({std.error}){stars}"),
statistic = NULL,
coef_omit = "Intercept")
| Â (1) | Â Â (2) | |
|---|---|---|
| educ_levelNo BA | −0.4 (0.1)*** | −0.4 (0.1)** |
| domicile | −0.1 (0.0)** | |
| Num.Obs. | 1893 | 1892 |
| R2 | 0.007 | 0.011 |
| R2 Adj. | 0.006 | 0.010 |
| AIC | 8507.5 | 8491.8 |
| BIC | 8524.1 | 8513.9 |
| Log.Lik. | −4250.728 | −4241.884 |
| RMSE | 2.07 | 2.06 |
Multivariate and interaction
#add Model 3 includes an interaction term between domicile and education level without BA
models <- list(
"Model 1" = lm(`How satisfied with the national government` ~ educ_level, data = france_data, weights = weight),
"Model 2" = lm(`How satisfied with the national government` ~ `domicile` + educ_level, data = france_data, weights = weight),
"Model 3" = lm(`How satisfied with the national government` ~ `domicile` + educ_level + `domicile`*educ_level, data = france_data, weights = weight))
modelplot(models, coef_omit = 'Interc') +
ggtitle("Plot 2: Coefficient Plot")
#create coefficient plot
modelsummary(models, fmt = 1,
estimate = c("{estimate} ({std.error}){stars}",
"{estimate} ({std.error}){stars}",
"{estimate} ({std.error}){stars}"),
statistic = NULL,
title = 'Table 2. Regression models predicting satisfied with the national government')
| Model 1 | Â Model 2 | Â Model 3 | |
|---|---|---|---|
| (Intercept) | 3.2 (0.1)*** | 3.4 (0.1)*** | 3.3 (0.2)*** |
| educ_levelNo BA | −0.4 (0.1)*** | −0.4 (0.1)** | −0.2 (0.3) |
| domicile | −0.1 (0.0)** | −0.1 (0.1) | |
| domicile × educ_levelNo BA | −0.1 (0.1) | ||
| Num.Obs. | 1893 | 1892 | 1892 |
| R2 | 0.007 | 0.011 | 0.011 |
| R2 Adj. | 0.006 | 0.010 | 0.009 |
| AIC | 8507.5 | 8491.8 | 8493.3 |
| BIC | 8524.1 | 8513.9 | 8521.1 |
| Log.Lik. | −4250.728 | −4241.884 | −4241.663 |
| RMSE | 2.07 | 2.06 | 2.06 |
france_data$`highest level of education`[france_data$edulvla==55] <- NA
france_data$edulvlb[france_data$edulvlb==5555] <- NA
france_data$educ.ba <- ifelse(france_data$essround<5 & france_data$`highest level of education`==5, 1,
ifelse(france_data$essround>=5 & france_data$edulvlb>600, 1, 0))
france_data$educ.ba <- ifelse(france_data$educ.ba == 1, "BA", "No BA")
# Doing new model & recoding variables of interest
library(effects)
## Loading required package: carData
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
#create interaction plot
model4 <- lm(`How satisfied with the national government` ~ `domicile` + educ.ba + `domicile`*educ.ba, data = france_data, weights = weight)
interaction_plot <- effect("domicile*educ.ba", model4, na.rm=TRUE)
plot(interaction_plot,
main="Plot3: Interaction effect",
xlab="1&2 Urban; 3&4&5 Rural",
ylab="satisfied with the national government")
interaction_plot
##
## domicile*educ.ba effect
## educ.ba
## domicile BA No BA
## 1 3.206520 2.930674
## 2 3.148833 2.806320
## 3 3.091147 2.681966
## 4 3.033460 2.557612
## 5 2.975774 2.433257