PART 1: Set Up Loading Packages
# List of packages
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer",
"fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer", "effects", "survey", "MASS", "kableExtra", "equatiomatic") # 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: viridisLite
##
##
## Attaching package: 'flextable'
##
##
## The following object is masked from 'package:purrr':
##
## compose
##
##
## 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 objects are masked from 'package:flextable':
##
## as_image, footnote
##
##
## 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] "rmarkdown" "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] "ggridges" "rmarkdown" "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" "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"
##
## [[11]]
## [1] "questionr" "ggridges" "rmarkdown" "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] "flextable" "questionr" "ggridges" "rmarkdown" "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" "flextable" "questionr" "ggridges" "rmarkdown"
## [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] "effects" "carData" "infer" "flextable" "questionr"
## [6] "ggridges" "rmarkdown" "knitr" "viridis" "viridisLite"
## [11] "fst" "RColorBrewer" "modelsummary" "lubridate" "forcats"
## [16] "stringr" "dplyr" "purrr" "readr" "tidyr"
## [21] "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [26] "grDevices" "utils" "datasets" "methods" "base"
##
## [[15]]
## [1] "survey" "survival" "Matrix" "grid" "effects"
## [6] "carData" "infer" "flextable" "questionr" "ggridges"
## [11] "rmarkdown" "knitr" "viridis" "viridisLite" "fst"
## [16] "RColorBrewer" "modelsummary" "lubridate" "forcats" "stringr"
## [21] "dplyr" "purrr" "readr" "tidyr" "tibble"
## [26] "ggplot2" "tidyverse" "stats" "graphics" "grDevices"
## [31] "utils" "datasets" "methods" "base"
##
## [[16]]
## [1] "MASS" "survey" "survival" "Matrix" "grid"
## [6] "effects" "carData" "infer" "flextable" "questionr"
## [11] "ggridges" "rmarkdown" "knitr" "viridis" "viridisLite"
## [16] "fst" "RColorBrewer" "modelsummary" "lubridate" "forcats"
## [21] "stringr" "dplyr" "purrr" "readr" "tidyr"
## [26] "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [31] "grDevices" "utils" "datasets" "methods" "base"
##
## [[17]]
## [1] "kableExtra" "MASS" "survey" "survival" "Matrix"
## [6] "grid" "effects" "carData" "infer" "flextable"
## [11] "questionr" "ggridges" "rmarkdown" "knitr" "viridis"
## [16] "viridisLite" "fst" "RColorBrewer" "modelsummary" "lubridate"
## [21] "forcats" "stringr" "dplyr" "purrr" "readr"
## [26] "tidyr" "tibble" "ggplot2" "tidyverse" "stats"
## [31] "graphics" "grDevices" "utils" "datasets" "methods"
## [36] "base"
##
## [[18]]
## [1] "equatiomatic" "kableExtra" "MASS" "survey" "survival"
## [6] "Matrix" "grid" "effects" "carData" "infer"
## [11] "flextable" "questionr" "ggridges" "rmarkdown" "knitr"
## [16] "viridis" "viridisLite" "fst" "RColorBrewer" "modelsummary"
## [21] "lubridate" "forcats" "stringr" "dplyr" "purrr"
## [26] "readr" "tidyr" "tibble" "ggplot2" "tidyverse"
## [31] "stats" "graphics" "grDevices" "utils" "datasets"
## [36] "methods" "base"
Loading Dataset
ess <- read_fst("All-ESS-Data.fst")
Subsetting to the UK
uk_data <- ess %>%
filter(cntry == "GB")
Creating and Cleaning main outcome variable
uk_data <- uk_data %>%
mutate(wrclmch = ifelse(wrclmch %in% c(6, 7, 8, 9), NA, wrclmch),
clmchng = ifelse(clmchng %in% c(7, 8, 9), NA, clmchng),
impenv = ifelse(impenv %in% c(7, 8, 9), NA, impenv),
ccrdprs = ifelse(ccrdprs %in% c(66, 77, 88, 99), NA, ccrdprs))
uk_data$climate <- scales::rescale(uk_data$wrclmch +
uk_data$clmchng +
uk_data$impenv +
uk_data$ccrdprs, to=c(0,100), na.rm=TRUE)
Quickly going to see the distribution of the new outcome variable ‘climate’
ggplot(uk_data, aes(x = climate)) +
geom_histogram(bins = 30, fill = "darkseagreen3", color = "black") +
theme_minimal() +
labs(title = "Histogram of Climate Attitudes (beliefs and concerns) Scale in the United Kingdom",
x = "Climate Attitudes Scale",
y = "Count")
## Warning: Removed 19098 rows containing non-finite values (`stat_bin()`).
uk_data$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
uk_data$year[uk_data$essround == i] <- replacements[i]
}
climate_avg <- uk_data %>%
group_by(year) %>%
summarize(climate_avg = mean(climate, na.rm = TRUE))
plot_zoom_climate <- ggplot(climate_avg, aes(x = year, y = climate_avg)) +
geom_point(aes(size = climate_avg, color = climate_avg), alpha = 0.7) +
geom_line(aes(group = 1), color = "blue", linetype = "dashed") +
labs(title = "Climate Attitude Scale Average by Year (UK)",
x = "Survey Year",
y = "Climate Attitude Scale Average") +
theme_minimal() +
theme(legend.position = "none")
print(plot_zoom_climate)
## Warning: Removed 9 rows containing missing values (`geom_point()`).
## Warning: Removed 9 rows containing missing values (`geom_line()`).
## `geom_line()`: Each group consists of only one observation.
## ℹ Do you need to adjust the group aesthetic?
#Okay so after looking at the variables separately on the ESS portal, I
saw that variables pertaining to climate change only got implemented
recently, with 3 of the variables first appearing in 2016, while 1
showed up in 2014. Due to this reason, I will not be using an ‘overtime
graph’ to look at climate change attitudes.
PART 2: Predictors and Data Summary (this will be seen on the context portion of the project) Our predictors are political stance and age range. Cleaning the Predictors
uk_data <- uk_data %>%
mutate(
polID = case_when(
lrscale %in% 0:3 ~ "Left",
lrscale %in% 7:10 ~ "Right",
lrscale %in% 4:6 ~ "Moderate",
lrscale %in% c(77, 88, 99) ~ NA_character_
),
# Recoding generation
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(yrbrn)
),
gen = factor(gen, levels = c("1", "2", "3", "4"),
labels = c("Interwar", "Baby Boomers", "Gen X", "Millennials")))
Quick Check
table(uk_data$polID)
##
## Left Moderate Right
## 3322 11672 3623
Turning predictors into numeric variables
d <- uk_data %>%
mutate(
polID_num = as.numeric(factor(polID, levels = c("Left", "Moderate", "Right"))),
gen_num = as.numeric(gen) # Assuming 'gen' is a factor with numeric levels
)
Creating Table
table1 <- datasummary_skim(d %>% dplyr::select(polID_num, gen_num, climate), 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 |
|---|---|---|---|---|---|---|---|
polID_num | 4 | 11 | 2.0 | 0.6 | 1.0 | 2.0 | 3.0 |
gen_num | 5 | 2 | 2.3 | 1.0 | 1.0 | 2.0 | 4.0 |
climate | 20 | 91 | 50.2 | 14.6 | 0.0 | 52.6 | 100.0 |
d <- d %>%
rename(
`Political Identity` = polID_num,
`Generations` = gen_num,
`Climate Attitudes` = climate
)
table1_v2 <- datasummary_skim(d %>% dplyr::select(`Political Identity`,`Generations`, `Climate Attitudes`), title = "Table 1. Descriptive statistics of main 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 |
|---|---|---|---|---|---|---|---|
Political Identity | 4 | 11 | 2.0 | 0.6 | 1.0 | 2.0 | 3.0 |
Generations | 5 | 2 | 2.3 | 1.0 | 1.0 | 2.0 | 4.0 |
Climate Attitudes | 20 | 91 | 50.2 | 14.6 | 0.0 | 52.6 | 100.0 |
Now saving as different output
flextable::save_as_docx(table1_v2, path = "summary_table_v2.docx", # change name to whatever you would like
width = 7.0, height = 7.0) # play around with dimensions
set_flextable_defaults(fonts_ignore=TRUE)
PART 3: Hypothesis with Infer (Apart of the ‘findings’ portion of the poster)
The first explanatory varibale we are going to use is political identity, a three catergory predictor (left, moderate, right). The response variable is climate, is a numeric variable, which will mean I will have to use the test statistic ANOVA.
Step 1
test_stat <- uk_data %>%
specify(explanatory = polID, # change variable name for explanatory variable
response = climate) %>% # change variable name for outcome of interest
hypothesize(null = "independence") %>%
calculate(stat = "F")
## Warning: Removed 19265 rows containing missing values.
print(test_stat$stat)
## [1] 16.54033
Step 2
null_dist <- uk_data %>%
specify(climate ~ polID) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "F")
## Warning: Removed 19265 rows containing missing values.
null_dist
## Response: climate (numeric)
## Explanatory: polID (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 2.78
## 2 2 1.22
## 3 3 0.186
## 4 4 1.20
## 5 5 1.75
## 6 6 0.301
## 7 7 1.48
## 8 8 0.0149
## 9 9 7.83
## 10 10 0.282
## # ℹ 990 more rows
Step 3
p_val <- null_dist %>% #
get_pvalue(obs_stat = test_stat, direction = "greater")
## 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
Step 4 (foudn in ‘Findings’ on the poster)
conf_int <- null_dist%>%
get_confidence_interval(level = 0.95, type = "percentile")
null_dist %>%
visualize(data, bins = 10, method = "simulation", dens_color = "black") +
shade_p_value(obs_stat = test_stat, direction = "greater") +
shade_confidence_interval(endpoints = conf_int)
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf
# Assuming 'test_stat' is your observed test statistic value
test_stat <- 16.54033
conf_int <- null_dist %>%
get_confidence_interval(level = 0.95, type = "percentile")
# Visualize the null distribution with manual x-axis limits
null_dist %>%
visualize(bins = 15, method = "simulation", dens_color = "black") +
geom_vline(aes(xintercept = test_stat), color = "red", linetype = "dashed", size = 1) +
shade_p_value(obs_stat = test_stat, direction = "greater") +
shade_confidence_interval(endpoints = conf_int) +
coord_cartesian(xlim = c(0, max(null_dist$stat) * 1.1)) + # Set manual x-axis limits
labs(title = "Simulation-Based Null Distribution",
x = "F statistic",
y = "Count")
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf
PART 4: Regression
uk_data$weight <- uk_data$dweight * uk_data$pweight
model1 <- lm(climate ~ polID, data = uk_data, weights = weight)
model2 <- lm(climate ~ polID + gen, data = uk_data, weights = weight)
model3 <- lm(climate ~ polID*gen, data = uk_data, 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")
| (1) | (2) | (3) | |
|---|---|---|---|
| polIDModerate | −3.5 (0.9)*** | −3.5 (0.9)*** | −8.4 (3.0)** |
| polIDRight | −5.5 (1.1)*** | −5.2 (1.2)*** | −8.7 (3.2)** |
| genBaby Boomers | 4.1 (1.1)*** | 0.4 (3.1) | |
| genGen X | 5.3 (1.2)*** | −1.2 (3.1) | |
| genMillennials | 3.8 (1.2)** | 1.0 (3.0) | |
| polIDModerate × genBaby Boomers | 5.0 (3.4) | ||
| polIDRight × genBaby Boomers | 1.9 (3.8) | ||
| polIDModerate × genGen X | 7.5 (3.5)* | ||
| polIDRight × genGen X | 9.0 (3.9)* | ||
| polIDModerate × genMillennials | 3.7 (3.4) | ||
| polIDRight × genMillennials | 0.3 (4.2) | ||
| Num.Obs. | 1714 | 1633 | 1633 |
| R2 | 0.015 | 0.029 | 0.036 |
| R2 Adj. | 0.013 | 0.026 | 0.029 |
| AIC | 14107.1 | 13415.8 | 13416.3 |
| BIC | 14128.8 | 13453.5 | 13486.4 |
| Log.Lik. | −7049.531 | −6700.878 | −6695.136 |
| RMSE | 14.29 | 14.11 | 14.07 |
interaction_plot <- effect("polID*gen", model3, na.rm=TRUE)
plot(interaction_plot,
main="Interaction effect",
xlab="Generation",
ylab="Climate attitudes scale")
models <- list(
"Model 1" = lm(climate ~ polID, data = uk_data, weights = weight),
"Model 2" = lm(climate ~ polID + gen, data = uk_data, weights = weight),
"Model 3" = lm(climate ~ polID*gen, data = uk_data, weights = weight)
)
modelsummary(models)
| Model 1 | Model 2 | Model 3 | |
|---|---|---|---|
| (Intercept) | 54.416 | 50.466 | 54.316 |
| (0.772) | (1.226) | (2.724) | |
| polIDModerate | −3.466 | −3.549 | −8.374 |
| (0.878) | (0.896) | (2.990) | |
| polIDRight | −5.527 | −5.179 | −8.659 |
| (1.140) | (1.171) | (3.231) | |
| genBaby Boomers | 4.074 | 0.361 | |
| (1.112) | (3.057) | ||
| genGen X | 5.325 | −1.155 | |
| (1.165) | (3.123) | ||
| genMillennials | 3.848 | 0.977 | |
| (1.185) | (3.041) | ||
| polIDModerate × genBaby Boomers | 5.049 | ||
| (3.372) | |||
| polIDRight × genBaby Boomers | 1.879 | ||
| (3.772) | |||
| polIDModerate × genGen X | 7.510 | ||
| (3.459) | |||
| polIDRight × genGen X | 8.987 | ||
| (3.940) | |||
| polIDModerate × genMillennials | 3.740 | ||
| (3.386) | |||
| polIDRight × genMillennials | 0.336 | ||
| (4.229) | |||
| Num.Obs. | 1714 | 1633 | 1633 |
| R2 | 0.015 | 0.029 | 0.036 |
| R2 Adj. | 0.013 | 0.026 | 0.029 |
| AIC | 14107.1 | 13415.8 | 13416.3 |
| BIC | 14128.8 | 13453.5 | 13486.4 |
| Log.Lik. | −7049.531 | −6700.878 | −6695.136 |
| RMSE | 14.29 | 14.11 | 14.07 |
equatiomatic::extract_eq(model3, use_coefs = TRUE)
\[ \operatorname{\widehat{climate}} = 54.32 - 8.37(\operatorname{polID}_{\operatorname{Moderate}}) - 8.66(\operatorname{polID}_{\operatorname{Right}}) + 0.36(\operatorname{gen}_{\operatorname{Baby\ Boomers}}) - 1.15(\operatorname{gen}_{\operatorname{Gen\ X}}) + 0.98(\operatorname{gen}_{\operatorname{Millennials}}) + 5.05(\operatorname{polID}_{\operatorname{Moderate}} \times \operatorname{gen}_{\operatorname{Baby\ Boomers}}) + 1.88(\operatorname{polID}_{\operatorname{Right}} \times \operatorname{gen}_{\operatorname{Baby\ Boomers}}) + 7.51(\operatorname{polID}_{\operatorname{Moderate}} \times \operatorname{gen}_{\operatorname{Gen\ X}}) + 8.99(\operatorname{polID}_{\operatorname{Right}} \times \operatorname{gen}_{\operatorname{Gen\ X}}) + 3.74(\operatorname{polID}_{\operatorname{Moderate}} \times \operatorname{gen}_{\operatorname{Millennials}}) + 0.34(\operatorname{polID}_{\operatorname{Right}} \times \operatorname{gen}_{\operatorname{Millennials}}) \]