# List of packages
packages <- c("tidyverse", "infer", "fst", "modelsummary", "effects", "survey", "MASS", "kableExtra", "flextable", "equatiomatic", "dplyr") # 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
## Warning: package 'effects' was built under R version 4.3.2
## Loading required package: carData
## Warning: package 'carData' was built under R version 4.3.2
## lattice theme set by effectsTheme()
## See ?effectsTheme for details.
## Warning: package 'survey' was built under R version 4.3.2
## 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"
##
## [[11]]
## [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")
country_averages <- ess %>%
filter(!(social %in% c(7, 8, 9))) %>%
group_by(cntry) %>%
summarize(avg_social = mean(social, na.rm = TRUE))
#Reorder the factor levels of 'cntry' based on 'avg_social'
country_averages$cntry <- reorder(country_averages$cntry, country_averages$avg_social)
p1 <- ggplot(country_averages, aes(x = cntry, y = avg_social, label = cntry)) +
geom_point(aes(color = avg_social), size = 3) +
geom_text(nudge_y = 1, size = 3) +
labs(
x = "Country",
y = "Average Support for Social Services (0-100)",
title = "Average Score for Support for Social Services In European Countries"
) +
theme_minimal() +
theme(legend.position = "none",
axis.text.x = element_blank(),
axis.title.x = element_text(face="bold", size=14))
p1
ggsave(filename = "plot1.pdf", plot = p1, device = "pdf", width = 6, height = 4)
We chose to use Norway as our country because after plotting the average score of support in social services for all European countries, we found that Norway was situated near the median. We wanted to investigate a typical case for support in social services because it can help to identify the underlying mechanisms behind the difference in opinions under ordinary or common circumstances. This can facilitate the generalisability of the results because most countries fall around the median.
norway_data <- ess %>%
filter(cntry == "NO")
df <- norway_data
df <- df %>%
mutate(
sbstrec = ifelse(sbstrec %in% c(7, 8, 9), NA, sbstrec),
sbbsntx = ifelse(sbbsntx %in% c(7, 8, 9), NA, sbbsntx),
sblazy = ifelse(sblazy %in% c(7, 8, 9), NA, sblazy),
sblwcoa = ifelse(sblwcoa %in% c(7, 8, 9), NA, sblwcoa))
#Creating and rescaling the support variable
df$social <- scales::rescale(df$sbstrec + df$sbbsntx + df$sblazy + df$sblwcoa, na.rm = TRUE, to = c(0, 100))
df <- df %>% filter(!is.na(social))
#Checking the distribution of scores in support for social services
ggplot(df, aes(x = social)) +
geom_histogram(bins = 30, fill = "blue", color = "black") +
theme_minimal() +
labs(title = "Histogram of Support for Support in Social Services Scale",
x = "Social Scale 0-100",
y = "Count")
#Left-right scale
df <- df %>%
mutate(lrscale = case_when(
lrscale %in% c(77, 88, 99) ~ NA_character_,
lrscale %in% 0:4 ~ "left",
lrscale == 5 ~ NA_character_, # Removed 5 because respondents are not either placed in right or left
lrscale %in% 6:10 ~ "right",
TRUE ~ NA_character_
)) %>%
filter(!is.na(lrscale))
table(df$lrscale) # Checking ESS round - Shows that the data is ESS round 8 = year 2016
##
## left right
## 1002 1274
#Education
df <- df %>%
mutate(edulvlb = case_when(
edulvlb %in% c(5555, 7777, 8888, 9999) ~ NA_character_,
edulvlb == 0 ~ "Not completed primary education",
edulvlb == 113 ~ "Primary education",
edulvlb %in% c(129, 212, 213, 221, 222, 223, 229, 311, 312, 313, 321, 322, 323, 412, 413, 421, 422, 423) ~ "Secondary education",
edulvlb %in% c(510, 520, 610, 620, 710, 720, 800) ~ "BA or more",
TRUE ~ as.character(edulvlb) # Convert numeric values to character
))
#The categories are created according to the ISCED to examine the effects of different levels of education on support for social services
unique(df$edulvlb)
## [1] NA "Secondary education"
## [3] "BA or more" "Primary education"
## [5] "Not completed primary education"
df <- df %>% filter(!is.na(edulvlb))
unique(df$edulvlb)
## [1] "Secondary education" "BA or more"
## [3] "Primary education" "Not completed primary education"
table(df$edulvlb)
##
## BA or more Not completed primary education
## 568 1
## Primary education Secondary education
## 12 560
table(df$essround) #
##
## 8
## 1141
#Summary table
norway_summary <- norway_data %>%
mutate(
social = ifelse(social %in% c(7, 8, 9), NA, social),
lrscale = ifelse(lrscale %in% c(77, 88, 99), NA, lrscale),
edulvlb = ifelse(edulvlb %in% c(5555, 7777, 8888, 9999), NA, edulvlb))
norway_summary <- norway_summary %>%
rename(
`Support for social services` = social,
`Placement on left right scale` = lrscale,
`Highest level of education` = edulvlb
)
summary_table <- datasummary_skim(norway_summary%>% dplyr::select(`Support for social services`,`Placement on left right scale`,`Highest level of education`), output = "flextable",
title ="Table 1: Descriptive Statistics for 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 |
|---|---|---|---|---|---|---|---|
Support for social services | 17 | 0 | 50.4 | 17.1 | 0.0 | 50.0 | 100.0 |
Placement on left right scale | 12 | 2 | 5.3 | 2.1 | 0.0 | 5.0 | 10.0 |
Highest level of education | 15 | 50 | 451.4 | 187.1 | 0.0 | 421.0 | 800.0 |
flextable::save_as_docx(summary_table, path = "summary_table.docx",
width = 7.0, height = 7.0)
From Table 1, it may be noted that the mean value is 50.4 points on the 0-100 support for social scale. The fact that the mean value falls approximately the middle of the scale implies that respondents, on average, do not strongly support or strongly not support social services, rather, they have a mixed opinion about it. Furthermore, it should be considered that the variable has a large standard deviation of 17.1 points. It conveys that the data is spread out and there is a diverse range of scores. In other words, there is a large variety of opinions about social services.
In addition, the mean on the placement on the 0-10 left-right scale is 5.3 points, suggesting that, on average, respondents do not explicitly identify to either the left or right party, and they would consider themselves a combination of both parties. The variable also has a large standard deviation of 2.1 points, to suggest a large range of people placing themselves in different positions on the left-right scale.
Lastly, the mean value of 451.4 points on the 0-800 highest level of education scale indicates that respondents, on average, have completed secondary education. Also, the large value for the standard deviation of 187.1 points illustrates a large spread of data, where respondents have completed a wide variety of education levels.
#Step 1: Test statistic
test_stat <- df %>%
specify(explanatory = lrscale,
response = social) %>%
hypothesize(null = "independence") %>%
calculate(stat = "t", order = c("left", "right"))
print(test_stat$stat)
## t
## 13.11556
alpha <- 0.05
c_val <- qt(1 - alpha/2, df = 1140, lower.tail = FALSE)
cat("Critical Value:", round(c_val, 3), "\n")
## Critical Value: -1.962
#Step 2: Simulate the null distribution
null_distribution <- df %>%
specify(explanatory = lrscale,
response = social) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "t", order = c("left", "right"))
#Step 3: P-value
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
#Step 4: Visualize
null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided")
conf_int <- null_distribution %>%
get_confidence_interval(level = 0.95, type = "percentile")
p2 <- null_distribution %>%
visualize() +
shade_p_value(obs_stat = test_stat, direction = "two-sided") +
shade_confidence_interval(endpoints = conf_int)
p2
ggsave(filename = "plot2.pdf", plot = p2, device = "pdf", width = 6, height = 4)
A t-test is applied here because the variables examined are a categorical variable (with two categories) and a numeric variable. The categorical explanatory variable is the left-right scale, and the numeric variable is the support for social services scale.
The t-statistic of 13.12 indicates the strength of this difference in terms of standard deviations. This magnitude is quite large and suggests a statistically significant difference in the means of support in social services for the “left” and “right” groups.
The t-statistic is greater than the critical value of -1.962, which provides enough evidence to reject the null hypothesis. It illustrates that people have different opinions on social services across the left-right scale.
A p-value of p<0.001 under the assumptions of frequentist hypothesis testing means there is strong evidence to reject the null hypothesis. This value is the probability of observing a result at least as extreme as the data collected with the assumption that there is no difference in opinions for social services between people who are placed differently on the left-right scale. It solidifies and backs the calculations of a t-statistic of 13.12 which is enough evidence to reject the null hypothesis. This is once again confirmed by visualization of the null distribution, where the test statistic falls outside the null distribution.
df$weight <- df$dweight * df$pweight
model1 <- lm(social ~ lrscale, data = df, weights = weight)
model2 <- lm(social ~ lrscale + edulvlb, data = df, weights = weight)
model3 <- lm(social ~ lrscale + edulvlb + lrscale*edulvlb, data = df, weights = weight)
models <- 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",
coef_rename = c("lrscaleright" = "Political Right", "edulvlbNot completed primary education" = "Not completed primary education", "edulvlbPrimary education" = "Primary education", "edulvlbSecondary education" = "Secondary education"),
title = "Table 2. Regression models predicting support for social services (0 to 100)")
models
| (1) | (2) | (3) | |
|---|---|---|---|
| Political Right | −13.3 (1.0)*** | −12.8 (1.0)*** | −16.8 (1.4)*** |
| Not completed primary education | −4.7 (16.9) | −2.7 (16.8) | |
| Primary education | −12.2 (4.9)* | −17.5 (6.9)* | |
| Secondary education | −4.5 (1.0)*** | −9.0 (1.5)*** | |
| Political Right:Primary education | 10.6 (9.8) | ||
| Political Right:Secondary education | 8.1 (2.0)*** | ||
| Num.Obs. | 1141 | 1141 | 1141 |
| R2 | 0.132 | 0.150 | 0.163 |
| R2 Adj. | 0.131 | 0.147 | 0.158 |
| AIC | 9711.3 | 9693.3 | 9680.6 |
| BIC | 9726.5 | 9723.6 | 9721.0 |
| Log.Lik. | −4852.669 | −4840.667 | −4832.322 |
| RMSE | 17.02 | 16.84 | 16.72 |
Model 1:
-13.3 Political Right: Respondents who are politically right are, on average, 13.3 points lower on the 0-100 support for social service scale than respondents who are politically left. This difference is statistically significant at the 0.001 significance level.
Model 2:
-12.8 Political Right: Respondents who are politically right are, on average, 12.8 points lower on the 0-100 support for social service scale than respondents who are politically left, while controlling for respondents’ highest level of education level. This difference is statistically significant at the 0.001 significance level.
-4.7 Not completed primary education: The correlation between support for social services and respondents who have not completed primary education is not statistically significant.
-12.2 Primary education: Respondents who have completed primary education are, on average, 12.2 points lower on the 0-100 support for social service scale than respondents who hold a BA or more, while controlling for respondents’ placement on the left-right scale. This difference is significant at the 0.05 significance level.
-4.5 Secondary education: Respondents who have completed secondary education are, on average, 4.5 points lower on the 0-100 support for social service scale than respondents who hold a BA or more, while controlling for respondents’ placement on the left-right scale. This difference is significant at the 0.001 significance level.
Model 3:
-16.8 Political Right: Respondents who are politically right are, on average, 16.8 points lower on the 0-100 support for social service scale than respondents who are politically left when education is 0 (received no education). This difference is statistically significant at the 0.001 significance level.
-2.7 Not completed primary education: The correlation between support for social services and respondents who have not completed primary education is not statistically significant.
-17.5 Primary education: Respondents who have completed primary education and are politically left are, on average, 17.5 points lower on the 0-100 support for social service scale than respondents who hold a BA or more and are politically left (left-right scale = 0). This difference is significant at the 0.05 significance level.
-9.0 Secondary education: Respondents who have completed secondary education and are politically left are, on average, 9.0 points lower on the 0-100 support for social service scale than respondents who hold a BA or more and are politically left. This difference is significant at the 0.001 significance level.
10.6 Political Right:Primary education: The interaction for respondents who are politically right and have completed primary education on the 0-100 support for social service scale is not statistically significant.
8.1 Political Right:Secondary education: In the interaction term, it can be observed that the effects of being politically right on the 0-100 support for social service scale are stronger for people who have completed secondary education compared to people who hold a BA or more. The interaction implies that respondents who are politically right and have completed secondary education have an average score on the support for social service 0-100 scale of 8.1 points higher than what would be expected for their placement on the left-right scale and education level independently. This difference is significant at the 0.001 significance level.
Model fits:
Number of Observations: Same across all models, ensuring a fair comparison.
A higher value for R-squared and adjusted R-squared indicates a better model because it suggests that the model is accounting for a higher proportion of the variance in the outcome variable. R-squared and adjusted R-squared both have an increase in proportion from model 1 to model 3. R-squared increases from 0.132 in model 1 to 0.163 in model 3, and adjusted R-squared increases from 0.131 in model 1 to 0.158 in model 3. 0.158 in model 3 suggests that the model takes into account 15.8% of the variance in support for social services. That is, placement of the left-right scale and education level can help to explain the differences in support for social services.
A lower value for AIC and BIC suggests a better model. Therefore model 3 with the lowest value of AIC (9680.6) and BIC (9721.0) implies that it is the better model out of the three possible models, taking into consideration the number of independent variables.
A more positive Log.Lik. value indicates a better model. Hence, model 3 with the highest value of -4832.322 is the better fit.
A lower value for RMSE suggests a better fit because it implies the model has a smaller magnitude of residuals. Therefore model 3 with the smallest value of 16.72 is the better fit.
Overall, these results suggest that model 3 is a better fit than models 1 and 2, where an interaction is present between education and left-right political scale position to affect support for social services.
country_names <- c(FR = "France", RO = "Romania", NO = "Norway", ES = "Spain", IL = "Israel", CY = "Cyprus")
selected_countries <- ess %>%
filter(cntry %in% names(country_names)) %>%
mutate(
lrscale = case_when(
lrscale %in% c(77, 88, 99) ~ NA,
lrscale %in% 0:4 ~ "left",
lrscale == 5 ~ NA,
lrscale %in% 6:10 ~ "right",
TRUE ~ NA
)
) %>%
filter(!is.na(lrscale))
country_lr <- selected_countries %>%
group_by(cntry, lrscale) %>%
summarise(avg_social = mean(social, na.rm = TRUE)) %>%
ungroup()
## `summarise()` has grouped output by 'cntry'. You can override using the
## `.groups` argument.
country_lr$cntry <- country_names[country_lr$cntry]
p3 <- ggplot(country_lr, aes(x = lrscale, y = avg_social, fill = lrscale)) +
geom_bar(stat = "identity") +
labs(
title = "Figure 2: Comparison of European Countries ",
subtitle = "For Support of Social Services based on Political Spectrum",
x = "Left-Right Scale",
y = "Average Value for Support for Social Services (0-100)"
) +
scale_fill_manual(values = c("left" = "blue", "right" = "red")) +
scale_y_continuous(limits = c(0, 60)) +
facet_wrap(~ cntry, ncol = 3) +
theme_minimal() +
theme(
legend.position = "none",
plot.title = element_text(size = 13, face = "bold"),
plot.subtitle = element_text(size = 13, face = "bold")
)
ggsave(filename = "plot3.pdf", plot = p3, device = "pdf", width = 30, height = 40)
print(p3)
Figure 2 illustrates the impact of the left-right political spectrum on the support for social services across a selection of European countries: Norway (NO), France (FR), Romania (RO), Spain (ES), Israel (IL), and Cyprus (CY). These countries were strategically chosen to represent a spectrum of average support for social services, ranging from low to high providing a comprehensive view. Specifically, France exhibited the lowest level, Romania was positioned around the first quartile, Spain aligned closely with Norway in the middle, Israel demonstrated support around the third quartile, and Cyprus reflected support in the upper quartile. Notably, consistent across all six European countries depicted in Figure 2 indicates that the political left exhibits higher support for social services compared to the political right. Consequently, our alternative hypothesis holds across different European countries across different levels of support for social service. This observed trend reinforces the association between political ideology and attitudes toward social services.