packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer",
"fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer") # add any you need here
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.3 ✔ 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
## 载入需要的程辑包:viridisLite
##
##
## 载入程辑包:'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")
france_data <- ess %>%
filter(cntry == "FR")
# Create a duplicate
df <- france_data
#cleaning main outcome variable
france_data <- france_data %>% mutate(happy = ifelse(happy %in% c(77, 88, 99), NA, happy))
# Clean predictors
france_data <- france_data %>%
mutate(maritalb = na_if(maritalb, 77),
maritalb = na_if(maritalb, 88),
maritalb = na_if(maritalb, 99)) %>%
mutate(
marital_status = case_when(
maritalb %in% c(1, 2) ~ "Married",
!is.na(maritalb) ~ "Not married",
TRUE ~ NA_character_
),
children = if_any(starts_with("rshipa"), ~.x == 2),
chldhhe = as.logical(chldhhe == 1),
children = case_when(
!is.na(children) ~ children,
!is.na(chldhhe) ~ chldhhe,
TRUE ~ FALSE
),
children_cat = if_else(children, "Children", "No Children")
)
# Display tables of the new and old children variables
table(france_data$children_cat)
##
## Children No Children
## 13277 5761
table(france_data$marital_status)
##
## Married Not married
## 5470 6173
# Filter df based on the criteria
df <- df %>% filter(!is.na(happy))
df <- df %>% filter(!is.na(maritalb))
df <- df %>% filter(!is.na(chldhhe))
###label
d <- df %>%
mutate(
happy = as.numeric(happy),
marital_status = as.numeric(maritalb),
children_cat = as.numeric(chldhhe)
)
d <- df %>%
rename(
`happiness level` = happy,
`marital status` = maritalb,
`household status` = chldhhe
)
table1_france <- datasummary_skim(d %>% dplyr::select(`happiness level`,`marital status`, `household status`), 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_france
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max |
|---|---|---|---|---|---|---|---|
happiness level | 13 | 0 | 7.3 | 3.4 | 0.0 | 8.0 | 88.0 |
marital status | 9 | 0 | 3.5 | 4.4 | 1.0 | 4.0 | 99.0 |
household status | 6 | 0 | 2.9 | 2.2 | 1.0 | 2.0 | 9.0 |
###hypothesis testing-marital status
test_stat <- df %>%
specify(explanatory = maritalb,
response = happy) %>%
hypothesize(null = "independence") %>%
calculate(stat = "slope")
## Message: The independence null hypothesis does not inform calculation of the
## observed statistic (a slope) and will be ignored.
print(test_stat$stat)
## maritalb
## -0.03684414
null_dist1 <- df %>%
specify(happy ~ maritalb) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "slope")
null_dist1
## Response: happy (numeric)
## Explanatory: maritalb (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 -0.00362
## 2 2 -0.000292
## 3 3 0.00926
## 4 4 0.00143
## 5 5 -0.00853
## 6 6 -0.00226
## 7 7 -0.00212
## 8 8 -0.00516
## 9 9 -0.00691
## 10 10 -0.00487
## # ℹ 990 more rows
p_val1 <- null_dist1 %>% #
get_pvalue(obs_stat = test_stat, direction = "greater")
p_val1
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 1
conf_int1 <- null_dist1%>%
get_confidence_interval(level = 0.95, type = "percentile")
null_dist1 %>%
visualize(data, bins = 10, method = "simulation", dens_color = "black") +
shade_p_value(obs_stat = test_stat, direction = "greater") +
shade_confidence_interval(endpoints = conf_int1)
test_stat1 <- 330.3334
conf_int1 <- null_dist1 %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_dist1 %>%
visualize(bins = 15, method = "simulation", dens_color = "black") +
geom_vline(aes(xintercept = test_stat1), color = "red", linetype = "dashed", size = 1) +
shade_p_value(obs_stat = test_stat, direction = "greater") +
shade_confidence_interval(endpoints = conf_int1) +
coord_cartesian(xlim = c(-0.05, max(null_dist1$stat) * 1.1)) +
labs(title = "Simulation-Based Null Distribution",
x = "stat",
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.
###Hypothesis testing-children
test_stat <- df %>%
specify(explanatory = chldhhe,
response = happy) %>%
hypothesize(null = "independence") %>%
calculate(stat = "slope")
## Message: The independence null hypothesis does not inform calculation of the
## observed statistic (a slope) and will be ignored.
print(test_stat$stat)
## chldhhe
## 0.04972634
null_dist2 <- df %>%
specify(happy ~ chldhhe) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "slope")
null_dist2
## Response: happy (numeric)
## Explanatory: chldhhe (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.0255
## 2 2 -0.00735
## 3 3 -0.0119
## 4 4 0.00892
## 5 5 0.00679
## 6 6 -0.0154
## 7 7 0.00606
## 8 8 0.00816
## 9 9 0.00941
## 10 10 -0.0186
## # ℹ 990 more rows
p_val2 <- null_dist2 %>% #
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_val2
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0
conf_int2 <- null_dist2 %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_dist2 %>%
visualize(data, bins = 10, method = "simulation", dens_color = "black") +
shade_p_value(obs_stat = test_stat, direction = "greater") +
shade_confidence_interval(endpoints = conf_int2)
## Warning in min(diff(unique_loc)): min里所有的参数都不存在; 回覆Inf
test_stat2 <- 330.3334
conf_int2 <- null_dist2 %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_dist2 %>%
visualize(bins = 15, method = "simulation", dens_color = "black") +
geom_vline(aes(xintercept = test_stat2), color = "red", linetype = "dashed", size = 1) +
shade_p_value(obs_stat = test_stat2, direction = "greater") +
shade_confidence_interval(endpoints = conf_int2) +
coord_cartesian(xlim = c(-0.05, max(null_dist1$stat) * 1.1)) +
labs(title = "Simulation-Based Null Distribution",
x = "stat",
y = "count")
## Warning in min(diff(unique_loc)): min里所有的参数都不存在; 回覆Inf
france_data <- france_data %>%
rename(
`happiness level` = happy,
`marital status` = maritalb,
`household composition` = chldhhe
)
models <- list(
"model1" <- lm(happy ~ maritalb, data = df, weights = weight),
"model2" <- lm(happy ~ chldhhe, data = df, weights = weight),
"model3" <- lm(happy ~ maritalb * chldhhe, data = df, weights = weight)
)
modelsummary(models)
| (1) | (2) | (3) | |
|---|---|---|---|
| (Intercept) | 7.513 | 7.924 | 7.149 |
| (0.227) | (0.239) | (0.425) | |
| maritalb | 0.026 | 0.235 | |
| (0.053) | (0.105) | ||
| chldhhe | -0.104 | 0.054 | |
| (0.062) | (0.090) | ||
| maritalb × chldhhe | -0.051 | ||
| (0.021) | |||
| Num.Obs. | 1917 | 1917 | 1917 |
| R2 | 0.000 | 0.001 | 0.005 |
| R2 Adj. | 0.000 | 0.001 | 0.003 |
| AIC | 12732.1 | 12729.5 | 12727.6 |
| BIC | 12748.8 | 12746.2 | 12755.4 |
| Log.Lik. | -6363.043 | -6361.738 | -6358.783 |
| RMSE | 3.42 | 3.44 | 3.47 |
modelsummary(models, vcov = "robust")
| (1) | (2) | (3) | |
|---|---|---|---|
| (Intercept) | 7.513 | 7.924 | 7.149 |
| (0.182) | (0.985) | (0.454) | |
| maritalb | 0.026 | 0.235 | |
| (0.107) | (0.338) | ||
| chldhhe | -0.104 | 0.054 | |
| (0.180) | (0.147) | ||
| maritalb × chldhhe | -0.051 | ||
| (0.072) | |||
| Num.Obs. | 1917 | 1917 | 1917 |
| R2 | 0.000 | 0.001 | 0.005 |
| R2 Adj. | 0.000 | 0.001 | 0.003 |
| AIC | 12732.1 | 12729.5 | 12727.6 |
| BIC | 12748.8 | 12746.2 | 12755.4 |
| Log.Lik. | -6363.043 | -6361.738 | -6358.783 |
| RMSE | 3.42 | 3.44 | 3.47 |
| Std.Errors | HC3 | HC3 | HC3 |
modelsummary(models, fmt = 3,
estimate = c("{estimate} ({std.error}){stars}",
"{estimate} ({std.error}){stars}",
"{estimate} ({std.error}){stars}"),
statistic = NULL,
coef_rename = c("maritalb" = "Marital Status", "chldhhe" = "Household Composition", "happy" = "Happiness Level"),
title = 'Table 2. Regression models predicting Happiness Level (0 to 100)')
| (1) | (2) | (3) | |
|---|---|---|---|
| (Intercept) | 7.513 (0.227)*** | 7.924 (0.239)*** | 7.149 (0.425)*** |
| Marital Status | 0.026 (0.053) | 0.235 (0.105)* | |
| Household Composition | -0.104 (0.062)+ | 0.054 (0.090) | |
| Marital Status:Household Composition | -0.051 (0.021)* | ||
| Num.Obs. | 1917 | 1917 | 1917 |
| R2 | 0.000 | 0.001 | 0.005 |
| R2 Adj. | 0.000 | 0.001 | 0.003 |
| AIC | 12732.1 | 12729.5 | 12727.6 |
| BIC | 12748.8 | 12746.2 | 12755.4 |
| Log.Lik. | -6363.043 | -6361.738 | -6358.783 |
| RMSE | 3.42 | 3.44 | 3.47 |
###Linear modelling visual diagnostics
par(mfrow = c(2,2))
plot(model2, pch = 19, col = scales::alpha("grey", .8), cex = .5)
###Regression equation
equatiomatic::extract_eq(model3, use_coefs = TRUE)
\[ \operatorname{\widehat{happy}} = 7.15 + 0.24(\operatorname{maritalb}) + 0.05(\operatorname{chldhhe}) - 0.05(\operatorname{maritalb} \times \operatorname{chldhhe}) \]