# List of packages
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer",
"fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer")
# 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
## [[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"
ess <- read_fst("All-ESS-Data.fst")
UnitedKingdom_data <- ess %>%
filter(cntry == "GB")
Here I will be cleaning other countries but keeping UK only for my research study.
write_fst(UnitedKingdom_data, "~/Desktop/SOC 252 H1 /R studio 252/UnitedKingdom_data.fst")
UK_filter <- read_fst("~/Desktop/SOC 252 H1 /R studio 252/UnitedKingdom_data.fst")
First, Cleanning the data and getting rid of NA values.
UK_data <- UK_filter %>%
mutate(
uemp3m = ifelse(uemp3m %in% c(7, 8, 9), NA, uemp3m),
edulvla = case_when(
essround < 5 & edulvla == 55 ~ NA_real_,
TRUE ~ edulvla
),
edulvlb = case_when(
essround >= 5 & edulvlb == 5555 ~ NA_real_,
TRUE ~ edulvlb
),
educ_level = case_when(
essround < 5 & edulvla == 5 ~ "BA",
essround >= 5 & edulvlb > 600 ~ "BA",
TRUE ~ "No BA"
),
geo = recode(as.character(domicil),
'1' = "Urban",
'2' = "Urban",
'3' = "Rural",
'4' = "Rural",
'5' = "Rural",
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_))
table(UK_data$geo)
##
## Rural Urban
## 14550 6376
table(UK_data$educ_level)
##
## BA No BA
## 6116 14863
table(UK_data$uemp3m)
##
## 1 2
## 4974 15944
Creating Summary table
Beacuse few variables above have been recoded into character, they cannot be formulated in the summary table. I create a new dataframe copy here to present the table.
UK_T_test <- UK_filter %>%
mutate(
uemp3m = ifelse(uemp3m %in% c(7, 8, 9), NA, uemp3m),
edulvla = case_when(
essround < 5 & edulvla == 55 ~ NA_real_,
TRUE ~ edulvla
),
edulvlb = case_when(
essround >= 5 & edulvlb == 5555 ~ NA_real_,
TRUE ~ edulvlb
),
educ_level = case_when(
essround < 5 & edulvla == 5 ~ "BA",
essround >= 5 & edulvlb > 600 ~ "BA",
TRUE ~ "No BA"
),
geo = recode(as.character(domicil),
'1' = "Urban",
'2' = "Urban",
'3' = "Rural",
'4' = "Rural",
'5' = "Rural",
'7' = NA_character_,
'8' = NA_character_,
'9' = NA_character_))
UK_data$edulvla[UK_data$edulvla == 55] <- NA
UK_data$edulvlb[UK_data$edulvlb == 5555] <- NA
# Recoding to 1 for "BA" and 0 for "No BA"
UK_data$educ_level <- ifelse(UK_data$essround < 5 & UK_data$edulvla == 5, 1,
ifelse(UK_data$essround >= 5 & UK_data$edulvlb > 600, 1, 0))
UK_data2 <- UK_data %>% filter(!is.na(educ_level))
UK_table <- UK_filter %>%
mutate(
edulvla = ifelse(edulvla %in% c(77, 88, 99), NA, edulvla),
edulvlb = ifelse(edulvlb %in% c(7777, 8888, 9999), NA, edulvlb),
uemp3m = ifelse(uemp3m %in% c(7, 8, 9), NA, uemp3m),
domicil = ifelse(domicil %in% c(7, 8, 9), NA, domicil)
)
summary_table <- datasummary_skim(UK_data %>% select(edulvla, edulvlb, domicil, uemp3m)
, 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 |
|---|---|---|---|---|---|---|---|
edulvla | 8 | 59 | 3.3 | 6.4 | 1.0 | 2.0 | 99.0 |
edulvlb | 19 | 43 | 444.0 | 757.0 | 0.0 | 323.0 | 8888.0 |
domicil | 8 | 0 | 2.9 | 1.0 | 1.0 | 3.0 | 9.0 |
uemp3m | 3 | 0 | 1.8 | 0.4 | 1.0 | 2.0 | 2.0 |
Renaming variables for clear visualization
UK_renamed <- UK_table %>%
rename(
`Education level (round 1-4)` = edulvla,
`Education level (round 5-10)` = edulvlb,
`Unemployed for 3 months or more` = uemp3m,
`place of residence` = domicil
)
summary_table_v2 <- datasummary_skim(UK_renamed %>% select(`Education level (round 1-4)`,`Education level (round 5-10)`, `Unemployed for 3 months or more`,`place of residence`), output = "flextable", title = "Table 1: Descriptive Statistics for Chosen 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 |
|---|---|---|---|---|---|---|---|
Education level (round 1-4) | 6 | 59 | 3.6 | 6.2 | 1.0 | 2.0 | 55.0 |
Education level (round 5-10) | 18 | 42 | 497.7 | 802.5 | 0.0 | 323.0 | 5555.0 |
Unemployed for 3 months or more | 3 | 0 | 1.8 | 0.4 | 1.0 | 2.0 | 2.0 |
place of residence | 6 | 0 | 2.9 | 0.9 | 1.0 | 3.0 | 5.0 |
The research will be using data taken from European Social Survey including 10 rounds of data record, while the targeted population is United Kingdom. The primary outcome is unemployment group who have been unemployed for at least three months or more and the predictors are education level and place of residence.
Visuals for data and method of analysis
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]
}
First, I do a graph to show the change of unemployment in recent years (2002-2020) in UK
UK_graph <- ess %>%
filter(cntry == "GB") %>%
select(cntry, year, yrbrn,uemp3m) %>%
mutate(
uemp3m = ifelse(uemp3m %in% c(7, 8, 9), NA, uemp3m)
)
unemployment_by_year <- UK_graph %>%
group_by(year) %>%
summarize(unemployment_mean_by_year = mean(uemp3m, na.rm = TRUE))
unemployment_by_year
## # A tibble: 10 × 2
## year unemployment_mean_by_year
## <dbl> <dbl>
## 1 2002 1.77
## 2 2004 1.76
## 3 2006 1.77
## 4 2008 1.78
## 5 2010 1.78
## 6 2012 1.77
## 7 2014 1.72
## 8 2016 1.75
## 9 2018 1.76
## 10 2020 1.74
ggplot(unemployment_by_year, aes(x = year, y = unemployment_mean_by_year)) +
geom_line(color = "#E0FFFF", size = 1) +
geom_point(color = "#FFA07A", size = 3) +
labs(title = "Figure 1. Unemployment in United Kingdom (2002-2020)",
x = "Year",
y = "Mean of unemployment (0-2 scale)") +
ylim(1, 2) +
theme_minimal()
## 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.
The visual shows the unemployment rate in United Kingdom from 2002-2020
on a scale of 1-2.
Continuing on, I want to compare the unemployment rate in United Kingdom to ESS baseline.
ess$uemp3m[ess$uemp3m %in% c(7, 8, 9)] <- NA
avg_unem_UK <- UK_graph %>%
group_by(year) %>%
summarize(mean_unemployment_UK = mean(uemp3m, na.rm = TRUE))
avg_unem_all_countries <- ess %>%
group_by(year) %>%
summarize(mean_unemployment_all = mean(uemp3m, na.rm = TRUE))
combined_data <- left_join(avg_unem_UK, avg_unem_all_countries, by = "year")
long_data <- combined_data %>%
pivot_longer(
cols = starts_with("mean_unemployment"),
names_to = "Unemployment_Type",
values_to = "Mean_Unemployment",
)
ggplot(long_data) +
geom_line(aes(x = year, y = Mean_Unemployment, color = Unemployment_Type), size = 1) +
geom_point(aes(x = year, y = Mean_Unemployment, color = Unemployment_Type), size = 3) +
labs(title = "Figure 1.1 United Kingdom and ESS baseline (2002-2020)",
x = "Year",
y = "Mean unemployment (1-2 scale)") +
ylim(1, 2) +
scale_color_manual(values = c("#EEAEEE", "#CDAF95"),
name = "Dataset",
labels = c("United Kingdom", "All ESS"),
breaks = c("mean_unemployment_UK", "mean_unemployment_all")) +
theme_minimal()
The graph above shows a comparison of unemployment rate in United
Kingdom compared to the ESS baseline data. As can be seen United Kingdom
has a lower unemployment rate compared to the ESS baseline through all
years from 2002 – 2020. It suggests that the world may be experiencing
the challenges of unemployment, but for comparison, the UK still has
above-average employment levels, meaning the UK job market still covers
a wide range of industries, and this diversity provides opportunities
for people with a variety of skills and qualifications, so individuals
create opportunities that contribute to a competitive and resilient
labor market.
Linear Models computing outcome and predictors
model1 <- lm(uemp3m ~ educ_level, family = binomial, data = UK_data)
## Warning: In lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
## extra argument 'family' will be disregarded
model2 <- lm(uemp3m ~ educ_level + geo, family = binomial, data = UK_data)
## Warning: In lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
## extra argument 'family' will be disregarded
model3 <- lm(uemp3m ~ educ_level + geo + educ_level*geo, family = binomial, data = UK_data)
## Warning: In lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
## extra argument 'family' will be disregarded
modelsummary(
list(model1, model2, model3))
| (1) | (2) | (3) | |
|---|---|---|---|
| (Intercept) | 1.753 | 1.759 | 1.761 |
| (0.004) | (0.004) | (0.004) | |
| educ_level | 0.030 | 0.030 | 0.024 |
| (0.007) | (0.007) | (0.008) | |
| geoUrban | −0.020 | −0.026 | |
| (0.006) | (0.008) | ||
| educ_level × geoUrban | 0.020 | ||
| (0.014) | |||
| Num.Obs. | 20526 | 20494 | 20494 |
| R2 | 0.001 | 0.001 | 0.002 |
| R2 Adj. | 0.001 | 0.001 | 0.001 |
| AIC | 23211.0 | 23161.0 | 23160.9 |
| BIC | 23234.8 | 23192.7 | 23200.6 |
| Log.Lik. | −11602.520 | −11576.482 | −11575.474 |
| RMSE | 0.43 | 0.43 | 0.43 |
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. Model Summary and Predictors Interacting')
| (1) | (2) | (3) | |
|---|---|---|---|
| (Intercept) | 1.8 (0.0)*** | 1.8 (0.0)*** | 1.8 (0.0)*** |
| educ_level | 0.0 (0.0)*** | 0.0 (0.0)*** | 0.0 (0.0)** |
| geoUrban | 0.0 (0.0)** | 0.0 (0.0)*** | |
| educ_level × geoUrban | 0.0 (0.0) | ||
| Num.Obs. | 20526 | 20494 | 20494 |
| R2 | 0.001 | 0.001 | 0.002 |
| R2 Adj. | 0.001 | 0.001 | 0.001 |
| AIC | 23211.0 | 23161.0 | 23160.9 |
| BIC | 23234.8 | 23192.7 | 23200.6 |
| Log.Lik. | −11602.520 | −11576.482 | −11575.474 |
| RMSE | 0.43 | 0.43 | 0.43 |
coef_omit = "Intercept"
There are multiple ways to determine which model is best fitted. Normally a better fit is indicated by a greater R-squared. Furthermore, the number of predictors in the model is taken into account by adjusted R-squared, which penalizes the addition of pointless variables. It’s a more cautious metric than R-squared and comes in handy when contrasting models with varying quantities of predictors. Based on the three models above, model 3 seems to be the best fitted model with a higher R-squared value and better adjusted R value.
Interaction plot
library(effects)
## Loading required package: carData
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
interaction_plot <- effect("educ_level*geo", model3, na.rm=TRUE)
plot(interaction_plot,
main="Figure 2. Interaction effect: Residence into Unemployment",
xlab="Education Level",
ylab="Unemployment")
In Figure 2., the interaction plot shows the comparison for people
living in urban areas and rural areas. Tis no significant interaction
effect if the lines that represent the various levels of a single
variable are almost parallel. An interaction effect present when the
lines are not parallel and are dynamic. Based on the visuals above, we
can claim there is no interaction effect between place of residence,
education, in related to unemployment rate.
Regression Equation
remotes::install_github("datalorax/equatiomatic")
## Skipping install of 'equatiomatic' from a github remote, the SHA1 (39e8c3ea) has not changed since last install.
## Use `force = TRUE` to force installation
equatiomatic::extract_eq(model3, use_coefs = TRUE)
\[ \operatorname{\widehat{uemp3m}} = 1.76 + 0.02(\operatorname{educ\_level}) - 0.03(\operatorname{geo}_{\operatorname{Urban}}) + 0.02(\operatorname{educ\_level} \times \operatorname{geo}_{\operatorname{Urban}}) \] The formula above is a linear regression model, forecasts uemp3m in response to the variables “educ_level” and “geoUrban,” as well as the way in which they interact. The intensity and direction of each variable’s link to the dependent variable are shown by the coefficients. The coefficient is 0.02 for “educ_level”, indicating the change in uemp3m for a one-unit change in “educ_level is positive while it is negative on the “geoUrban”. The “educ_level x geoUrban” suggest that there is a positive change with the two variables affecting together.
T-Test to determine whethere reject null hypothesis or not.
test_stat <- UK_T_test %>%
specify(explanatory = educ_level,
response = uemp3m) %>%
hypothesize(null = "independence") %>%
calculate(stat = "t")
## Warning: Removed 61 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
## 4.528819
null_distribution <- UK_T_test %>%
specify(explanatory = educ_level,
response = uemp3m) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "t")
## Warning: Removed 61 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.
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
null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided")
null_distribution
## Response: uemp3m (numeric)
## Explanatory: educ_level (factor)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 2.00
## 2 2 -0.0199
## 3 3 0.625
## 4 4 0.0516
## 5 5 -1.16
## 6 6 0.159
## 7 7 -0.0913
## 8 8 1.06
## 9 9 -0.305
## 10 10 -0.732
## # ℹ 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) +
labs(title = "Figure 3. Simulation-Based Null Distribution",
x="Stat",
y="Count")
In Figure 3, it shows the null distribution alongside the observed
T-test statistic, where I compute education level as predictor and the
unemployment as outcome. T-test is used to assess whether there is a
significant difference between the means of two groups and their
relationship. According to graph and the rejection region in the Figure
3, it is evident to reject the null hypothesis with a p-value of 0 is
found.