load packages
# List of packages
packages <- c("tidyverse", "infer", "fst", "modelsummary", "effects", "survey", "MASS", "kableExtra", "flextable") # add any you need here
# 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"
packages <- c("tidyverse", "infer", "fst") # add any you need here
# 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)
## [[1]]
## [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"
##
## [[2]]
## [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"
##
## [[3]]
## [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"
Loading dataset
ess <- read_fst("All-ESS-Data.fst")
subsetting for country
GreatBritan_data <- ess %>%
filter(cntry == "GB")
# not a bad practice to create a duplicate in case you need to backtrack or use for different purposes
GBdf <- GreatBritan_data
year clean
table(ess$essround)
##
## 1 2 3 4 5 6 7 8 9 10
## 42359 47537 43000 56752 52458 54673 40185 44387 49519 59685
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]
}
generations
GreatBritan_data <- GreatBritan_data %>%
mutate(
# Recoding age variable, setting 999 to NA
age = ifelse(agea == 999, NA, agea),
# Recoding cohort variable, setting years before 1900 and after 2000 to NA
cohort = ifelse(yrbrn < 1930 | yrbrn > 2000, NA, yrbrn),
# Recoding generational cohorts based on year of birth
gen = case_when(
yrbrn %in% 1900:1945 ~ "1",
yrbrn %in% 1946:1964 ~ "2",
yrbrn %in% 1965:1979 ~ "3",
yrbrn %in% 1980:1996 ~ "4",
TRUE ~ as.character(cohort) # Keeping other values as character if they do not fit the ranges
),
# Converting cohort to a factor with labels
gen = factor(gen,
levels = c("1", "2", "3", "4"),
labels = c("Interwar", "Baby_Boomers", "Gen_X", "Millennials"))
)
table(GreatBritan_data$age)
##
## 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
## 100 177 167 213 171 201 200 193 204 246 236 266 249 269 295 339 315 338 335 316
## 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
## 371 401 359 349 357 387 380 347 318 362 338 321 342 354 348 326 335 336 306 346
## 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
## 326 360 351 322 342 349 358 337 318 352 314 342 345 312 331 323 291 286 265 264
## 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
## 265 223 244 207 180 184 186 182 172 121 101 95 89 63 61 66 28 19 12 8
## 95 96 97 98 123
## 4 1 1 2 1
table(GreatBritan_data$gen)
##
## Interwar Baby_Boomers Gen_X Millennials
## 5129 6723 5160 3535
Cleaning Education
# Re-coding education
GreatBritan_data <- GreatBritan_data %>%
mutate(
# Set 'other' to NA for rounds 1-4
edulvla = case_when(
essround < 5 & edulvla == 55 ~ NA_real_,
TRUE ~ edulvla
),
# Set 'other' to NA for rounds 5 and later
edulvlb = case_when(
essround >= 5 & edulvlb == 5555 ~ NA_real_,
TRUE ~ edulvlb
),
# Create educ_level column
educ_level = case_when(
essround < 5 & edulvla == 5 ~ "BA",
essround >= 5 & edulvlb > 600 ~ "BA",
TRUE ~ "No_BA"
)
)
# View the table of educ_level
table(GreatBritan_data$educ_level)
##
## BA No_BA
## 6116 14863
Cleaning Gender
GreatBritan_data <- GreatBritan_data %>%
mutate(
gndr = case_when(
gndr == 1 ~ "Male",
gndr == 2 ~ "Female",
TRUE ~ as.character(gndr)
)
) %>%
mutate(
gndr = ifelse(gndr %in% c("9"), NA, gndr)
)
table(GreatBritan_data$gndr)
##
## Female Male
## 11565 9402
Cleaning: confidance in political participation
GreatBritan_data <- GreatBritan_data %>%
mutate(
cptppola = ifelse(cptppola %in% c(7, 8, 9), NA, cptppola),
)
table(GreatBritan_data$cptppola)
##
## 1 2 3 4 5
## 1530 1552 1449 562 196
# 1 - not at all confident
# 2 - a little confident
# 3 - quite confident
# 4 - very confident
# 5 - completely confident
Context step 3 Table 1
relevant_cols <- c("cptppola", "gen", "educ_level")
relevant_data <- GreatBritan_data[, relevant_cols]
# Calculate descriptive statistics
summary_stats <- summary(relevant_data)
# Displaying the descriptive statistics
print(summary_stats)
## cptppola gen educ_level
## Min. :1.000 Interwar :5129 Length:20979
## 1st Qu.:1.000 Baby_Boomers:6723 Class :character
## Median :2.000 Gen_X :5160 Mode :character
## Mean :2.308 Millennials :3535
## 3rd Qu.:3.000 NA's : 432
## Max. :5.000
## NA's :15690
##Findings Step 3 #Table 3
# First, aggregate the data to calculate the mean confidence for each combination of generation and education level
GreatBritain_data_aggregated <- GreatBritan_data %>%
group_by(gen, educ_level) %>%
summarise(mean_confidence = mean(cptppola, na.rm = TRUE))
## `summarise()` has grouped output by 'gen'. You can override using the `.groups`
## argument.
# Now, use ggplot to create the plot
ggplot(GreatBritain_data_aggregated, aes(x = gen, y = mean_confidence, fill = educ_level)) +
geom_bar(stat = "identity", position = "dodge") +
labs(title = "Table 3",
subtitle = "Average Confidence in Political Participation by Education Level and Generation",
x = "Generation",
y = "Average Confidence") +
scale_fill_manual(values = c("BA" = "darkblue", "No_BA" = "lightblue")) +
theme_minimal()
Calculating T-stat
test_stat <- GreatBritan_data %>%
specify(explanatory = educ_level, # change variable name for explanatory variable
response = cptppola) %>% # change variable name for outcome of interest
hypothesize(null = "independence") %>%
calculate(stat = "t")
## Warning: Removed 15690 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
## 20.43571
Simulate the Null Dsitribution
null_distribution <- GreatBritan_data %>%
specify(explanatory = educ_level,
response = cptppola) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>% # only line we are adding, use reps = 1000 as standard
calculate(stat = "t")
## Warning: Removed 15690 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.
Calculate P-value
p_val <- null_distribution %>% # replace name here if you assigned something other than null_distribution above
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
null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided")
null_distribution
## Response: cptppola (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 -1.81
## 2 2 0.750
## 3 3 -0.816
## 4 4 0.494
## 5 5 1.12
## 6 6 -0.482
## 7 7 1.10
## 8 8 0.219
## 9 9 -0.157
## 10 10 0.491
## # ℹ 990 more rows
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)
linear modelling visual
model1 <- lm(cptppola ~ gen, data = GreatBritan_data)
model2 <- lm(cptppola ~ gen + educ_level, data = GreatBritan_data)
modelsummary(
list(model1, model2),
fmt = 1,
estimate = c( "{estimate} ({std.error}){stars}",
"{estimate} ({std.error}){stars}"),
statistic = NULL,
coef_omit = "Intercept")
| (1) | (2) | |
|---|---|---|
| genBaby_Boomers | 0.3 (0.0)*** | 0.2 (0.0)*** |
| genGen_X | 0.4 (0.0)*** | 0.2 (0.0)*** |
| genMillennials | 0.2 (0.1)*** | 0.1 (0.0) |
| educ_levelNo_BA | −0.7 (0.0)*** | |
| Num.Obs. | 5011 | 5011 |
| R2 | 0.012 | 0.086 |
| R2 Adj. | 0.011 | 0.085 |
| AIC | 15217.4 | 14829.4 |
| BIC | 15250.0 | 14868.5 |
| Log.Lik. | −7603.721 | −7408.687 |
| RMSE | 1.10 | 1.06 |
try again for 3 models
model1 <- lm(cptppola ~ gen, data = GreatBritan_data)
model2 <- lm(cptppola ~ gen + educ_level, data = GreatBritan_data)
model3 <- lm(cptppola ~ gen * educ_level, data = GreatBritan_data)
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) | |
|---|---|---|---|
| genBaby_Boomers | 0.3 (0.0)*** | 0.2 (0.0)*** | 0.0 (0.1) |
| genGen_X | 0.4 (0.0)*** | 0.2 (0.0)*** | 0.1 (0.1) |
| genMillennials | 0.2 (0.1)*** | 0.1 (0.0) | −0.2 (0.1)* |
| educ_levelNo_BA | −0.7 (0.0)*** | −0.9 (0.1)*** | |
| genBaby_Boomers × educ_levelNo_BA | 0.2 (0.1)* | ||
| genGen_X × educ_levelNo_BA | 0.2 (0.1) | ||
| genMillennials × educ_levelNo_BA | 0.4 (0.1)** | ||
| Num.Obs. | 5011 | 5011 | 5011 |
| R2 | 0.012 | 0.086 | 0.087 |
| R2 Adj. | 0.011 | 0.085 | 0.086 |
| AIC | 15217.4 | 14829.4 | 14825.5 |
| BIC | 15250.0 | 14868.5 | 14884.2 |
| Log.Lik. | −7603.721 | −7408.687 | −7403.762 |
| RMSE | 1.10 | 1.06 | 1.06 |