packages <- c("tidyverse", "infer", "fst", "modelsummary", "effects", "survey", "MASS", "kableExtra", "flextable", "equatiomatic")
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: 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"
ess <- read_fst("All-ESS-Data.fst")
Recoding:
#filtering to country of interest
france_data <- ess %>%
filter(cntry == "FR") %>%
mutate(
#cleaning outcome trstplt (trust in politics)
trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
#cleaning main predictor education level
edulvla = edulvla %>%
na_if(55) %>%
na_if(77) %>%
na_if(88) %>%
na_if(99),
edulvlb = edulvlb %>%
na_if(5555) %>%
na_if(7777) %>%
na_if(8888) %>%
na_if(9999),
#changed BA and No BA to a numeric for later coding
educ.ba = case_when(
essround < 5 & edulvla == 5 ~ 1,
essround >= 5 & edulvlb > 600 ~ 1,
TRUE ~ 0
),
#cleaning our secondary predictor happiness
stflife = ifelse(stflife %in% c(77, 88, 99), NA, stflife)
)
df <- france_data
france_data <- france_data %>% filter(!is.na(trstplt))
france_data <- france_data %>% filter(!is.na(educ.ba))
france_data <- france_data %>% filter(!is.na(stflife))
table(france_data$trstplt)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 2637 1564 2732 2957 2577 3609 1459 850 362 70 49
table(france_data$educ.ba)
##
## 0 1
## 14669 4197
table(france_data$stflife)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 538 263 664 1013 1076 2551 1890 3316 4328 1730 1497
Graphs for Outcome
#putting data year range from 2016-2022
df$year <- NA
replacements <- c(2016, 2017, 2018, 2019, 2020, 2021, 2022)
for(i in 1:10){
df$year[df$essround == i] <- replacements[i]
}
trstplt_avg <- df %>%
group_by(year) %>%
summarize(trstplt_avg = mean(trstplt, na.rm = TRUE))
plot_zoom_trstplt <- ggplot(trstplt_avg, aes(x = year, y = trstplt_avg)) +
geom_point(aes(size = trstplt_avg, color = trstplt_avg), alpha = 0.7) +
geom_line(aes(group = 1), color = "blue", linetype = "dashed") +
labs(title = "Trust in Politics Average by Year in France",
x = "Survey Year",
y = "Trust in Politics Average") +
theme_minimal() +
theme(legend.position = "none")
print(plot_zoom_trstplt)
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 1 row containing missing values (`geom_line()`).
plot_full_scale_trstplt <- ggplot(trstplt_avg, aes(x = year, y = trstplt_avg)) +
geom_point(aes(size = trstplt_avg, color = trstplt_avg), alpha = 0.7) +
geom_line(aes(group = 1), color = "blue", linetype = "dashed") +
labs(title = "Trust in Politics Average by Year in France",
x = "Survey Year",
y = "Trust in Politics Average") +
theme_minimal() +
theme(legend.position = "none") +
scale_y_continuous(limits = c(0, 10))
print(plot_full_scale_trstplt)
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 1 row containing missing values (`geom_line()`).
Data summary table:
d <- df %>%
# Convert factors/characters to numeric
mutate(
trstplt = as.numeric(trstplt),
stflife = as.numeric(stflife),
educ_ba_num = as.numeric(educ.ba)
)
table1 <- datasummary_skim(d %>% dplyr::select(trstplt, stflife, educ_ba_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.
table1
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max |
|---|---|---|---|---|---|---|---|
trstplt | 12 | 1 | 3.3 | 2.2 | 0.0 | 3.0 | 10.0 |
stflife | 12 | 0 | 6.4 | 2.4 | 0.0 | 7.0 | 10.0 |
educ_ba_num | 2 | 0 | 0.2 | 0.4 | 0.0 | 0.0 | 1.0 |
#relabeling and titling our data summary table
d <- d %>%
rename(
`Trust in Politics` = trstplt,
`Life Satisfaction` = stflife,
`Educational Attainment` = educ_ba_num
)
table1_v2 <- datasummary_skim(d %>% dplyr::select(`Trust in Politics`,`Life Satisfaction`, `Educational Attainment`), title = "Table 1: Descriptive Statistics of Variables", 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.
table1_v2
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max |
|---|---|---|---|---|---|---|---|
Trust in Politics | 12 | 1 | 3.3 | 2.2 | 0.0 | 3.0 | 10.0 |
Life Satisfaction | 12 | 0 | 6.4 | 2.4 | 0.0 | 7.0 | 10.0 |
Educational Attainment | 2 | 0 | 0.2 | 0.4 | 0.0 | 0.0 | 1.0 |
Hypothesis Testing with Infer:
#Step 1: calculating the test statistics
#subsetting to country of interest
france_data <- ess %>%
filter(cntry == "FR") %>%
mutate(
#cleaning outcome trstplt (trust in politics)
trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
#cleaning main predictor education level
edulvla = edulvla %>%
na_if(55) %>%
na_if(77) %>%
na_if(88) %>%
na_if(99),
edulvlb = edulvlb %>%
na_if(5555) %>%
na_if(7777) %>%
na_if(8888) %>%
na_if(9999),
#changing educ.ba back to a categorical variable in order to run t test
educ.ba = case_when(
essround < 5 & edulvla == 5 ~ 'BA',
essround >= 5 & edulvlb > 600 ~ 'BA',
TRUE ~ 'No BA'
),
#cleaning our secondary filter satisfaction with democracy
stflife = ifelse(stflife %in% c(77, 88, 99), NA, stflife)
)
df <- france_data
test_stat <- df %>%
specify(explanatory = educ.ba, # change variable name for explanatory variable
response = trstplt) %>% # change variable name for outcome of interest
hypothesize(null = "independence") %>%
calculate(stat = "t")
## Warning: Removed 146 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
## 14.29895
#Step 2: Simulating the null distribution
null_dist <- df %>%
specify(explanatory = educ.ba,
response = trstplt) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "t")
## Warning: Removed 146 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.
null_dist
## Response: trstplt (numeric)
## Explanatory: educ.ba (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 2.19
## 2 2 -0.581
## 3 3 -0.00129
## 4 4 -0.108
## 5 5 -0.939
## 6 6 -0.286
## 7 7 -0.260
## 8 8 -0.132
## 9 9 2.34
## 10 10 0.0630
## # ℹ 990 more rows
#Step 3: Calculating the p-value
p_val <- null_dist %>%
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
Given the p-value, (0), it represents that there is strong evidence to reject the null hypothesis.
#visualizing
null_dist %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided")
null_dist
## Response: trstplt (numeric)
## Explanatory: educ.ba (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 2.19
## 2 2 -0.581
## 3 3 -0.00129
## 4 4 -0.108
## 5 5 -0.939
## 6 6 -0.286
## 7 7 -0.260
## 8 8 -0.132
## 9 9 2.34
## 10 10 0.0630
## # ℹ 990 more rows
conf_int <- null_dist %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_dist %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided") +
shade_confidence_interval(endpoints = conf_int)+
labs(title = "Figure 1. Null Distribution",
x = "T statistic",
y = "Count")
null_dist
## Response: trstplt (numeric)
## Explanatory: educ.ba (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 2.19
## 2 2 -0.581
## 3 3 -0.00129
## 4 4 -0.108
## 5 5 -0.939
## 6 6 -0.286
## 7 7 -0.260
## 8 8 -0.132
## 9 9 2.34
## 10 10 0.0630
## # ℹ 990 more rows
Regression Modelling (model summary):
df$weight <- df$dweight * df$pweight
model1 <- lm(trstplt ~ educ.ba, data = df, weights = weight)
model2 <- lm(trstplt ~ educ.ba + stflife, data = df, weights = weight)
model3 <- lm(trstplt ~ educ.ba + stflife*educ.ba, data = df, 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,
title = 'Table 2. Regression models output')
| Â (1) | Â Â (2) | Â Â (3) | |
|---|---|---|---|
| (Intercept) | 3.8 (0.0)*** | 2.4 (0.1)*** | 2.3 (0.1)*** |
| educ.baNo BA | −0.5 (0.0)*** | −0.4 (0.0)*** | −0.3 (0.1)* |
| stflife | 0.2 (0.0)*** | 0.2 (0.0)*** | |
| educ.baNo BA × stflife | 0.0 (0.0) | ||
| Num.Obs. | 18892 | 18866 | 18866 |
| R2 | 0.011 | 0.054 | 0.054 |
| R2 Adj. | 0.011 | 0.054 | 0.054 |
| AIC | 84476.5 | 83518.1 | 83518.9 |
| BIC | 84500.0 | 83549.5 | 83558.1 |
| Log.Lik. | −42235.247 | −41755.043 | −41754.439 |
| RMSE | 2.15 | 2.10 | 2.10 |
Boxplot (visualization)
df <- france_data %>%
mutate(
trstplt = ifelse(trstplt %in% c(77, 88, 99), NA, trstplt),
#cleaning our main predictor education level
edulvla = edulvla %>%
na_if(55) %>%
na_if(77) %>%
na_if(88) %>%
na_if(99),
edulvlb = edulvlb %>%
na_if(5555) %>%
na_if(7777) %>%
na_if(8888) %>%
na_if(9999),
educ.ba = case_when(
essround < 5 & edulvla == 5 ~ 'BA',
essround >= 5 & edulvlb > 600 ~ 'BA',
TRUE ~ 'No BA'
)
)
figure2plot <- ggplot(df, aes(x = reorder(educ.ba, -trstplt, FUN=median), y = trstplt, fill = educ.ba)) +
geom_boxplot() +
theme_minimal() +
theme(legend.position = "none") +
labs(title = "Figure 2. Boxplot Comparison for Trust in Politics and Educational Attainment (France)",
x = "Educational Attainment",
y = " Trust in Politics Scale (0-10)")
figure2plot
## Warning: Removed 146 rows containing non-finite values (`stat_boxplot()`).