packages <- c("tidyverse", "infer", "fst", "modelsummary", "broom","remotes", "flextable","tidyverse", "modelsummary", "forcats", "RColorBrewer", "effects", "fst", "viridis", "knitr", "kableExtra", "rmarkdown", "ggridges", "viridis", "questionr")
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
## Warning: package 'remotes' was built under R version 4.3.2
##
## Attaching package: 'flextable'
##
## The following object is masked from 'package:purrr':
##
## compose
## 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.
## Loading required package: viridisLite
##
## 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] "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] "broom" "modelsummary" "fst" "infer" "lubridate"
## [6] "forcats" "stringr" "dplyr" "purrr" "readr"
## [11] "tidyr" "tibble" "ggplot2" "tidyverse" "stats"
## [16] "graphics" "grDevices" "utils" "datasets" "methods"
## [21] "base"
##
## [[6]]
## [1] "remotes" "broom" "modelsummary" "fst" "infer"
## [6] "lubridate" "forcats" "stringr" "dplyr" "purrr"
## [11] "readr" "tidyr" "tibble" "ggplot2" "tidyverse"
## [16] "stats" "graphics" "grDevices" "utils" "datasets"
## [21] "methods" "base"
##
## [[7]]
## [1] "flextable" "remotes" "broom" "modelsummary" "fst"
## [6] "infer" "lubridate" "forcats" "stringr" "dplyr"
## [11] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [16] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [21] "datasets" "methods" "base"
##
## [[8]]
## [1] "flextable" "remotes" "broom" "modelsummary" "fst"
## [6] "infer" "lubridate" "forcats" "stringr" "dplyr"
## [11] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [16] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [21] "datasets" "methods" "base"
##
## [[9]]
## [1] "flextable" "remotes" "broom" "modelsummary" "fst"
## [6] "infer" "lubridate" "forcats" "stringr" "dplyr"
## [11] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [16] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [21] "datasets" "methods" "base"
##
## [[10]]
## [1] "flextable" "remotes" "broom" "modelsummary" "fst"
## [6] "infer" "lubridate" "forcats" "stringr" "dplyr"
## [11] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [16] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [21] "datasets" "methods" "base"
##
## [[11]]
## [1] "RColorBrewer" "flextable" "remotes" "broom" "modelsummary"
## [6] "fst" "infer" "lubridate" "forcats" "stringr"
## [11] "dplyr" "purrr" "readr" "tidyr" "tibble"
## [16] "ggplot2" "tidyverse" "stats" "graphics" "grDevices"
## [21] "utils" "datasets" "methods" "base"
##
## [[12]]
## [1] "effects" "carData" "RColorBrewer" "flextable" "remotes"
## [6] "broom" "modelsummary" "fst" "infer" "lubridate"
## [11] "forcats" "stringr" "dplyr" "purrr" "readr"
## [16] "tidyr" "tibble" "ggplot2" "tidyverse" "stats"
## [21] "graphics" "grDevices" "utils" "datasets" "methods"
## [26] "base"
##
## [[13]]
## [1] "effects" "carData" "RColorBrewer" "flextable" "remotes"
## [6] "broom" "modelsummary" "fst" "infer" "lubridate"
## [11] "forcats" "stringr" "dplyr" "purrr" "readr"
## [16] "tidyr" "tibble" "ggplot2" "tidyverse" "stats"
## [21] "graphics" "grDevices" "utils" "datasets" "methods"
## [26] "base"
##
## [[14]]
## [1] "viridis" "viridisLite" "effects" "carData" "RColorBrewer"
## [6] "flextable" "remotes" "broom" "modelsummary" "fst"
## [11] "infer" "lubridate" "forcats" "stringr" "dplyr"
## [16] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [21] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [26] "datasets" "methods" "base"
##
## [[15]]
## [1] "knitr" "viridis" "viridisLite" "effects" "carData"
## [6] "RColorBrewer" "flextable" "remotes" "broom" "modelsummary"
## [11] "fst" "infer" "lubridate" "forcats" "stringr"
## [16] "dplyr" "purrr" "readr" "tidyr" "tibble"
## [21] "ggplot2" "tidyverse" "stats" "graphics" "grDevices"
## [26] "utils" "datasets" "methods" "base"
##
## [[16]]
## [1] "kableExtra" "knitr" "viridis" "viridisLite" "effects"
## [6] "carData" "RColorBrewer" "flextable" "remotes" "broom"
## [11] "modelsummary" "fst" "infer" "lubridate" "forcats"
## [16] "stringr" "dplyr" "purrr" "readr" "tidyr"
## [21] "tibble" "ggplot2" "tidyverse" "stats" "graphics"
## [26] "grDevices" "utils" "datasets" "methods" "base"
##
## [[17]]
## [1] "rmarkdown" "kableExtra" "knitr" "viridis" "viridisLite"
## [6] "effects" "carData" "RColorBrewer" "flextable" "remotes"
## [11] "broom" "modelsummary" "fst" "infer" "lubridate"
## [16] "forcats" "stringr" "dplyr" "purrr" "readr"
## [21] "tidyr" "tibble" "ggplot2" "tidyverse" "stats"
## [26] "graphics" "grDevices" "utils" "datasets" "methods"
## [31] "base"
##
## [[18]]
## [1] "ggridges" "rmarkdown" "kableExtra" "knitr" "viridis"
## [6] "viridisLite" "effects" "carData" "RColorBrewer" "flextable"
## [11] "remotes" "broom" "modelsummary" "fst" "infer"
## [16] "lubridate" "forcats" "stringr" "dplyr" "purrr"
## [21] "readr" "tidyr" "tibble" "ggplot2" "tidyverse"
## [26] "stats" "graphics" "grDevices" "utils" "datasets"
## [31] "methods" "base"
##
## [[19]]
## [1] "ggridges" "rmarkdown" "kableExtra" "knitr" "viridis"
## [6] "viridisLite" "effects" "carData" "RColorBrewer" "flextable"
## [11] "remotes" "broom" "modelsummary" "fst" "infer"
## [16] "lubridate" "forcats" "stringr" "dplyr" "purrr"
## [21] "readr" "tidyr" "tibble" "ggplot2" "tidyverse"
## [26] "stats" "graphics" "grDevices" "utils" "datasets"
## [31] "methods" "base"
##
## [[20]]
## [1] "questionr" "ggridges" "rmarkdown" "kableExtra" "knitr"
## [6] "viridis" "viridisLite" "effects" "carData" "RColorBrewer"
## [11] "flextable" "remotes" "broom" "modelsummary" "fst"
## [16] "infer" "lubridate" "forcats" "stringr" "dplyr"
## [21] "purrr" "readr" "tidyr" "tibble" "ggplot2"
## [26] "tidyverse" "stats" "graphics" "grDevices" "utils"
## [31] "datasets" "methods" "base"
ess <- read_fst("All-ESS-Data.fst")
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]
}
bulgaria_data <- ess %>%
filter(cntry == "BG") %>%
mutate(
happy = ifelse(happy %in% c(77, 88, 99), NA, happy)
)
df <- bulgaria_data
table(bulgaria_data$happy)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 588 509 678 1016 1131 2577 1610 1793 1563 752 877
table(df$happy)
##
## 0 1 2 3 4 5 6 7 8 9 10
## 588 509 678 1016 1131 2577 1610 1793 1563 752 877
datasummary_skim(bulgaria_data %>% select(happy))
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max | ||
|---|---|---|---|---|---|---|---|---|
| happy | 12 | 1 | 5.5 | 2.6 | 0.0 | 6.0 | 10.0 |
happy_year <- bulgaria_data %>%
group_by(year) %>%
summarize(mean_happy = mean(trstplt, na.rm = TRUE))
happy_year
## # A tibble: 6 × 2
## year mean_happy
## <dbl> <dbl>
## 1 2006 5.78
## 2 2008 5.14
## 3 2010 4.83
## 4 2012 5.13
## 5 2018 5.09
## 6 2020 2.61
ggplot(happy_year, aes(x = year, y = mean_happy)) +
geom_line(color = "blue", size = 1) + # Line to show the trend
geom_point(color = "red", size = 3) + # Points to highlight each year's value
labs(title = "Happiness in Bulgaria (2002-2020)",
x = "Survey Year",
y = "Happiness (0-10)") +
ylim(0, 10) +
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.
bulgaria_data %>%
ggplot(aes(x = happy, y = as.factor(year), fill = as.factor(year))) +
geom_density_ridges() + # geometry used for visualizing
labs(title = "Happiness in Bulgaria across Survey Years",
x = "Happiness (0-10)", y = "Survey Year",
fill = "Survey Year") +
theme_minimal()
## Picking joint bandwidth of 0.463
## Warning: Removed 146 rows containing non-finite values
## (`stat_density_ridges()`).
bulgaria_data <- bulgaria_data %>%
mutate(happi = happy,
satislife = stflife) %>%
mutate(across(c("happi", "satislife"),
~ na_if(.x, 77) %>% na_if(88) %>% na_if(99))) %>%
# Apply the reverse coding
mutate(across(c("happi", "satislife"), ~ 77 - .x ))
bulgaria_data$hedonicbg <- scales::rescale(bulgaria_data$happi + bulgaria_data$satislife, to=c(0,100), na.rm=TRUE)
df <- bulgaria_data %>% filter(!is.na(hedonicbg))
df$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018)
for(i in 1:10){
df$year[df$essround == i] <- replacements[i]
}
hedonic_avg <- df %>%
group_by(year) %>%
summarize(hedonic_avg = mean(hedonicbg, na.rm = TRUE))
plot_zoom_hedonic <- ggplot(hedonic_avg, aes(x = year, y = hedonic_avg)) +
geom_point(aes(size = hedonic_avg, color = hedonic_avg), alpha = 0.7) +
geom_line(aes(group = 1), color = "blue", linetype = "dashed") +
labs(title = "Hedonic Wellbeing Scale Average by Year (Bulgaria)",
x = "Survey Year",
y = "Hedonic Wellbeing Scale Average") +
theme_minimal() +
theme(legend.position = "none")
print(plot_zoom_hedonic)
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 1 row containing missing values (`geom_line()`).
did not include 2020 as stflife was not asked
ess$year <- NA
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018)
for(i in 1:9){
ess$year[ess$essround == i] <- replacements[i]
}
ess <- ess %>%
mutate(happi = happy,
satislife = stflife) %>%
mutate(across(c("happi", "satislife"),
~ na_if(.x, 77) %>% na_if(88) %>% na_if(99))) %>%
# Apply the reverse coding
mutate(across(c("happi", "satislife"), ~ 77 - .x ))
# Now you can calculate 'schwartzauth' after the NA recoding
ess$hedonic <- scales::rescale(ess$happi+
ess$satislife, to=c(0,100), na.rm=TRUE)
ess_cleaned <- ess %>%
mutate(
hedonic = hedonic,
year = as.factor(year) # Ensure year is a factor
) %>%
filter(!is.na(hedonic))
# Calculating yearly averages for each country
yearly_hedonic_avg <- ess_cleaned %>%
group_by(cntry, year) %>%
summarize(avg_hedonic = mean(hedonic), .groups = 'drop')
# Subset for specific countries and overall ESS baseline
specific_countries_hedonic <- yearly_hedonic_avg %>%
filter(cntry %in% c("HU", "FR", "ES", "DE", "SE", "BG", "UA"))
ess_baseline_hedonic <- ess_cleaned %>%
group_by(year) %>%
summarize(avg_hedonic = mean(hedonic), .groups = 'drop') %>%
mutate(cntry = "ESS Baseline")
# Combining specific countries with ESS baseline
combined_data_hedonic <- rbind(specific_countries_hedonic, ess_baseline_hedonic)
# Plotting the spaghetti plot for authoritarianism
ggplot(combined_data_hedonic, aes(x = year, y = avg_hedonic, group = cntry, color = cntry)) +
geom_line() +
scale_color_manual(values = c("HU" = "darkgreen", "FR" = "red", "ES" = "yellow", "DE" = "orange", "SE" = "blue", "BG" = "pink","UA" = "brown", "ESS Baseline" = "black")) +
labs(title = "Average Hedonic Wellbeing Score by Year for Selected Countries and ESS Baseline",
x = "Year",
y = "Hedonic Wellbeing Score (100 being low)") +
theme_minimal() +
theme(legend.position = "right")
df <- bulgaria_data %>%
mutate(
edulvla = edulvla %>%
na_if(55) %>%
na_if(88),
edulvlb = edulvlb %>%
na_if(5555) %>%
na_if(7777) %>%
na_if(8888),
educ_lvl = case_when(
essround < 5 & edulvla == 5 ~ 1,
essround >= 5 & edulvlb > 600 ~ 1,
TRUE ~ 0),
health = ifelse(health %in% c(7, 8, 9), NA, health)
)
table(df$educ_lvl)
##
## 0 1
## 10138 3102
table(df$health)
##
## 1 2 3 4 5
## 2437 5204 3828 1393 368
d <- df %>%
mutate(
educ_num = as.numeric(educ_lvl),
health_num = as.numeric(health),
hedonicbg_num = as.numeric(hedonicbg)
)
datasummary_skim(d %>% select(educ_lvl, health, hedonicbg_num))
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max | ||
|---|---|---|---|---|---|---|---|---|
| educ_lvl | 2 | 0 | 0.2 | 0.4 | 0.0 | 0.0 | 1.0 | |
| health | 6 | 0 | 2.4 | 1.0 | 1.0 | 2.0 | 5.0 | |
| hedonicbg_num | 22 | 2 | 47.8 | 24.2 | 0.0 | 50.0 | 100.0 |
flext <- datasummary_skim(d %>% dplyr::select(educ_num, health_num, hedonicbg_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.
flext
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max |
|---|---|---|---|---|---|---|---|
educ_num | 2 | 0 | 0.2 | 0.4 | 0.0 | 0.0 | 1.0 |
health_num | 6 | 0 | 2.4 | 1.0 | 1.0 | 2.0 | 5.0 |
hedonicbg_num | 22 | 2 | 47.8 | 24.2 | 0.0 | 50.0 | 100.0 |
d <- d %>%
rename(
`Educational Attainment` = educ_num,
`Health` = health_num,
`Hedonic Wellbeing` = hedonicbg_num,
)
table1_v2 <- datasummary_skim(d %>% dplyr::select(`Educational Attainment`, `Health`, `Hedonic Wellbeing`), 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 |
|---|---|---|---|---|---|---|---|
Educational Attainment | 2 | 0 | 0.2 | 0.4 | 0.0 | 0.0 | 1.0 |
Health | 6 | 0 | 2.4 | 1.0 | 1.0 | 2.0 | 5.0 |
Hedonic Wellbeing | 22 | 2 | 47.8 | 24.2 | 0.0 | 50.0 | 100.0 |
flextable::save_as_docx(table1_v2, path = "summary_table_v2.docx",
width = 7.0, height = 7.0)
set_flextable_defaults(fonts_ignore=TRUE)
print(table1_v2, preview = "pdf")
## a flextable object.
## col_keys: ` `, `Unique (#)`, `Missing (%)`, `Mean`, `SD`, `Min`, `Median`, `Max`
## header has 1 row(s)
## body has 3 row(s)
## original dataset sample:
## Unique (#) Missing (%) Mean SD Min Median Max
## 1 Educational Attainment 2 0 0.2 0.4 0.0 0.0 1.0
## 2 Health 6 0 2.4 1.0 1.0 2.0 5.0
## 3 Hedonic Wellbeing 22 2 47.8 24.2 0.0 50.0 100.0
model1 <- lm(hedonicbg ~ health, data = df)
model2 <- lm(hedonicbg ~ educ_lvl, data = df)
coefficients <- coef(model1)
print(coefficients)
## (Intercept) health
## 22.15438 10.71419
Interpretation: [insert here]
tidy(model1)
## # A tibble: 2 × 5
## term estimate std.error statistic p.value
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) 22.2 0.498 44.4 0
## 2 health 10.7 0.192 55.7 0
summary(model1)
##
## Call:
## lm(formula = hedonicbg ~ health, data = df)
##
## Residuals:
## Min 1Q Median 3Q Max
## -70.725 -14.297 -0.011 15.703 67.131
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 22.1544 0.4985 44.45 <2e-16 ***
## health 10.7142 0.1923 55.73 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 21.7 on 13012 degrees of freedom
## (226 observations deleted due to missingness)
## Multiple R-squared: 0.1927, Adjusted R-squared: 0.1926
## F-statistic: 3105 on 1 and 13012 DF, p-value: < 2.2e-16
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(model1, use_coefs = TRUE)
\[ \operatorname{\widehat{hedonicbg}} = 22.15 + 10.71(\operatorname{health}) \]
modelsummary(
list(model1),
fmt = 1,
estimate = c( "{estimate} ({std.error}){stars}"),
statistic = NULL,
coef_omit = "Intercept")
| (1) | |
|---|---|
| health | 10.7 (0.2)*** |
| Num.Obs. | 13014 |
| R2 | 0.193 |
| R2 Adj. | 0.193 |
| AIC | 117035.4 |
| BIC | 117057.8 |
| Log.Lik. | −58514.684 |
| RMSE | 21.70 |
test_stat <- df %>%
specify(explanatory = health,
response = hedonicbg) %>%
hypothesize(null = "independence") %>%
calculate(stat = "slope")
## Warning: Removed 226 rows containing missing values.
## Message: The independence null hypothesis does not inform calculation of the
## observed statistic (a slope) and will be ignored.
print(test_stat$stat)
## health
## 10.71419
null_distribution <- df %>%
specify(explanatory = health,
response = hedonicbg) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "slope")
## Warning: Removed 226 rows containing missing values.
null_distribution
## Response: hedonicbg (numeric)
## Explanatory: health (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.214
## 2 2 -0.147
## 3 3 0.269
## 4 4 -0.244
## 5 5 -0.233
## 6 6 -0.0305
## 7 7 0.120
## 8 8 0.164
## 9 9 -0.0870
## 10 10 0.0186
## # ℹ 990 more rows
p_val <- null_distribution %>% #
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
conf_int <- null_distribution%>%
get_confidence_interval(level = 0.95, type = "percentile")
null_distribution %>%
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
test_stat <- 10.71419
conf_int <- null_distribution %>%
get_confidence_interval(level = 0.95, type = "percentile")
# Visualize the null distribution with manual x-axis limits
null_distribution %>%
visualize(bins = 20, 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_distribution$stat) * 1.1)) + # Set manual x-axis limits
labs(title = "Simulation-Based Null Distribution",
x = "F statistic",
y = "Count")
## Warning in min(diff(unique_loc)): no non-missing arguments to min; returning
## Inf
null_distribution
## Response: hedonicbg (numeric)
## Explanatory: health (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.214
## 2 2 -0.147
## 3 3 0.269
## 4 4 -0.244
## 5 5 -0.233
## 6 6 -0.0305
## 7 7 0.120
## 8 8 0.164
## 9 9 -0.0870
## 10 10 0.0186
## # ℹ 990 more rows
df <- df %>%
mutate(
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"
)
)
#add edulvlb data set and recode them into "No BA" and "BA"
table(df$educ_level)
##
## BA No BA
## 3102 10138
df$weight <- df$dweight * df$pweight
model1 <- lm(hedonicbg ~ health, data = df, weights = weight)
model2 <- lm(hedonicbg ~ educ_level + health, data = df, weights = weight)
model3 <- lm(hedonicbg ~ educ_level*health, 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,
coef_omit = "Intercept")
| (1) | (2) | (3) | |
|---|---|---|---|
| health | 10.5 (0.2)*** | 10.1 (0.2)*** | 9.2 (0.5)*** |
| educ_levelNo BA | 7.4 (0.5)*** | 5.2 (1.2)*** | |
| educ_levelNo BA × health | 1.0 (0.5)+ | ||
| Num.Obs. | 13014 | 13014 | 13014 |
| R2 | 0.181 | 0.197 | 0.197 |
| R2 Adj. | 0.181 | 0.197 | 0.197 |
| AIC | 119075.1 | 118815.0 | 118813.2 |
| BIC | 119097.5 | 118844.9 | 118850.6 |
| Log.Lik. | −59534.547 | −59403.520 | −59401.601 |
| RMSE | 21.70 | 21.48 | 21.48 |
models <- list(
"Model 1" = lm(hedonicbg ~ health, data = df, weights = weight),
"Model 2" = lm(hedonicbg ~ educ_level + health, data = df, weights = weight),
"Model 3" = lm(hedonicbg ~ educ_level*health, data = df, weights = weight))
modelplot(models, coef_omit = 'Interc') +
ggtitle("Plot 2: Coefficient Plot")
model_summary <- modelsummary(models, fmt = 1,
estimate = c("{estimate} ({std.error}){stars}",
"{estimate} ({std.error}){stars}",
"{estimate} ({std.error}){stars}"),
statistic = NULL,
title = 'Table 2. Regression models predicting Hedonic Wellbeing')
model_summary
| Model 1 | Model 2 | Model 3 | |
|---|---|---|---|
| (Intercept) | 22.7 (0.5)*** | 17.9 (0.6)*** | 19.6 (1.1)*** |
| health | 10.5 (0.2)*** | 10.1 (0.2)*** | 9.2 (0.5)*** |
| educ_levelNo BA | 7.4 (0.5)*** | 5.2 (1.2)*** | |
| educ_levelNo BA × health | 1.0 (0.5)+ | ||
| Num.Obs. | 13014 | 13014 | 13014 |
| R2 | 0.181 | 0.197 | 0.197 |
| R2 Adj. | 0.181 | 0.197 | 0.197 |
| AIC | 119075.1 | 118815.0 | 118813.2 |
| BIC | 119097.5 | 118844.9 | 118850.6 |
| Log.Lik. | −59534.547 | −59403.520 | −59401.601 |
| RMSE | 21.70 | 21.48 | 21.48 |
df$edulvla[df$edulvla==55] <- NA
df$edulvlb[df$edulvlb==5555] <- NA
df$educba <- ifelse(df$essround<5 & df$edulvla==5, 1,
ifelse(df$essround>=5 & df$edulvlb>600, 1, 0))
df$educba <- ifelse(df$educba == 1, "BA", "No BA")
model4 <- lm(hedonicbg ~ health + educba + health*educba, data = df, weights = weight)
interaction_plot <- effect("health*educba", model4, na.rm=TRUE)
plot(interaction_plot,
main="Plot 3: Interaction effect",
xlab="Health",
ylab="Hedonic Wellbeing")
interaction_plot
##
## health*educba effect
## educba
## health BA No BA
## 1 28.87229 35.11285
## 2 38.11986 45.37437
## 3 47.36744 55.63589
## 4 56.61502 65.89741
## 5 65.86259 76.15893