# List of packages
packages <- c("tidyverse", "modelsummary", "forcats", "RColorBrewer",
"fst", "viridis", "knitr", "rmarkdown", "ggridges", "viridis", "questionr", "flextable", "infer", "broom") # 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.4 ✔ 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
## 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"
##
## [[14]]
## [1] "broom" "infer" "flextable" "questionr" "ggridges"
## [6] "rmarkdown" "knitr" "viridis" "viridisLite" "fst"
## [11] "RColorBrewer" "modelsummary" "lubridate" "forcats" "stringr"
## [16] "dplyr" "purrr" "readr" "tidyr" "tibble"
## [21] "ggplot2" "tidyverse" "stats" "graphics" "grDevices"
## [26] "utils" "datasets" "methods" "base"
ess <- read_fst("All-ESS-Data.fst")
replacements <- c(2002, 2004, 2006, 2008, 2010, 2012, 2014, 2016, 2018, 2020)
for(i in 1:10){
ess$year[ess$essround == i] <- replacements[i]
}
# Filter for France and remove rows with NAs in 'happy' and 'netustm'
france_data <- ess %>%
filter(cntry == "FR") %>%
mutate(
happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
netustm = ifelse(netustm %in% c(6666, 7777, 8888, 9999), NA, netustm),
uemp3m = ifelse(uemp3m %in% c(7, 8, 9), NA, uemp3m),
)
Making sure there are no NAs before proceeding.
# Remove rows with NAs from the entire dataset
cleaned_data <- ess %>%
filter(!is.na(happy),
!is.na(netustm),
!is.na(uemp3m))
# Double-checking unique values and quick distribution for the entire dataset
unique(cleaned_data$happy)
## [1] 5 8 9 7 2 6 10 3 0 4 1 77 88 99
unique(cleaned_data$netustm)
## [1] 180 120 6666 30 90 11 360 60 150 210 20 105 140 9999 420
## [16] 16 300 240 45 40 135 270 600 15 540 70 480 510 195 14
## [31] 50 25 12 145 330 190 10 100 19 75 450 390 55 99 250
## [46] 4 2 165 115 205 225 110 80 260 200 5 325 13 18 61
## [61] 230 315 660 95 720 490 1320 0 900 35 8888 1200 125 92 380
## [76] 960 1020 340 770 570 245 290 840 65 3 1080 63 310 630 170
## [91] 130 255 160 400 215 7777 1115 500 1440 158 545 295 249 85 285
## [106] 405 345 385 320 121 375 750 690 153 123 370 365 435 39 870
## [121] 780 410 659 1430 185 43 69 220 219 122 305 243 542 1 183
## [136] 239 980 302 880 46 1230 831 265 175 445 372 168 128 460 615
## [151] 430 68 485 610 204 248 1140 1170 590 235 895 59 975 976 280
## [166] 775 194 155 263 202 525 495 939 1167 539 848 777 972 828 612
## [181] 1141 1205 604 957 605 818 1150 810 555 181 241 363 601 62 602
## [196] 361 847 1232 813 727 1119 1234 1231 1145 725 899 841 98 91 614
## [211] 316 1179 350 530 470 1260 7 49 203 719 34 28 647 395 794
## [226] 89 640 761 873 988 650 83 129 29 860 488 275 242 1380 901
## [241] 244 48 366 182 915 722 304 494 159 484 671 427 550 902 306
## [256] 152 549 930 189 489 1000 735 6 23 21 86 31 27 147 44
## [271] 186 483 213 154 149 138 119 611 124 440 93 565 343 106 126
## [286] 335 179 585 458 272 560 107 188 238 199 8 465 655 96 276
## [301] 507 71 264 625 421 482 36 301 433 362 765 227 218 192 637
## [316] 94 398 131 97 127 261 9 118 78 425 246 620 133 520 608
## [331] 88 595 599 38 308 64 196 271 177 132 990 1038 74 505 481
## [346] 740 665 940 732 333 143 359 311 72 278 368 338 328 745 256
## [361] 580 609 198 377 533 492 299 47 970 675 642 113 721 284 58
## [376] 422 419 108 479 193 312 346 754 749 680 141 303 890 1050 730
## [391] 24 416 645 337 1284 760 321 282 327 1240 254 527 258 1343 358
## [406] 1250 603 1439 653 216 535 486 820 403 455 959 1220 1410 1078 950
## [421] 790 298 313 1010 925 920 778 538 352 575 267 631 1196 800 556
## [436] 662 850 237 693 214 710 696 522 415 252 477 274 355 528 635
## [451] 1060 222 699 397 197 73 487 670 269 342 423
unique(cleaned_data$uemp3m)
## [1] 1 2 7 8 9
table(cleaned_data$happy)
##
## 0 1 2 3 4 5 6 7 8 9 10 77 88
## 1057 826 2034 3793 4827 14169 13632 28600 42690 24380 16816 162 290
## 99
## 315
#Data Summary Table for 'netustm' and 'happy' in France
france_data <- ess %>%
filter(cntry == "FR") %>%
mutate(
happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
netustm = ifelse(netustm %in% c(6666, 7777, 8888, 9999), NA, netustm),
uemp3m = ifelse(uemp3m %in% c(7, 8, 9), NA, uemp3m)
) %>%
select(netustm, happy, uemp3m)
datasummary_skim(france_data)
| Unique (#) | Missing (%) | Mean | SD | Min | Median | Max | ||
|---|---|---|---|---|---|---|---|---|
| netustm | 80 | 76 | 189.7 | 170.1 | 0.0 | 120.0 | 1380.0 | |
| happy | 12 | 0 | 7.2 | 1.8 | 0.0 | 8.0 | 10.0 | |
| uemp3m | 3 | 0 | 1.6 | 0.5 | 1.0 | 2.0 | 2.0 |
1st Visualization
# Filter and compute average happiness level for all countries except France
all_except_france <- ess %>%
filter(cntry != "FR") %>%
mutate(happy = ifelse(happy %in% c(77, 88, 99), NA, happy)) %>%
group_by(essround) %>%
summarize(average_happy = mean(happy, na.rm = TRUE))
# Filter and compute average happiness level for France
france_data <- ess %>%
filter(cntry == "FR") %>%
mutate(happy = ifelse(happy %in% c(77, 88, 99), NA, happy)) %>%
group_by(essround) %>%
summarize(average_happy = mean(happy, na.rm = TRUE))
# Create a data frame with "All Except France" and "France" categories
combined_data <- rbind(
mutate(all_except_france, Country = "All Except France"),
mutate(france_data, Country = "France")
)
# Plot the average happiness level for "All Except France" and "France" in a grouped bar graph
ggplot(data = combined_data, aes(x = essround, y = average_happy, color = Country)) +
geom_line() +
scale_color_manual(values = c("France" = "red", "All Except France" = "blue")) +
labs(title = "Comparing Average Happiness: France vs Other Countries",
x = "ESS Round",
y = "Average Happiness Level") +
scale_x_continuous(breaks = seq(min(ess$essround), max(ess$essround), by = 1))
2nd Visualization
france_data <- ess %>%
filter(cntry == "FR") %>%
mutate(
happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
netustm = ifelse(netustm %in% c(6666, 7777, 8888, 9999), NA, netustm)
) %>%
select(netustm, happy)
ggplot(france_data, aes(x = netustm, fill = cut(happy, breaks = 10))) +
geom_histogram(position = "identity", alpha = 0.7, bins = 30) +
labs(title = "Distribution of Internet Use and Happiness in France (All Rounds)",
x = "Internet Use",
y = "Frequency",
fill = "Happiness Level") +
theme_minimal()
## Warning: Removed 14556 rows containing non-finite values (`stat_bin()`).
Important Note: to assign the appropriate test statistic, please refer to the summary table presented during lecture (specifically, slide 24)
happy_stat <- france_data %>%
specify(explanatory = netustm,
response = happy) %>%
calculate(stat = "slope")
## Warning: Removed 14563 rows containing missing values.
print(happy_stat$stat)
## netustm
## 1.553155e-05
Interpretation: The result of the linear regression analysis for the relationship between ‘netustm’ and ‘happy’ indicates that, on average, a one-unit increase in the ‘netustm’ variable is associated with a very small change in the ‘happy’ variable. The estimated slope, approximately 1.553e-05, suggests a positive relationship, implying that as the time spent on the internet (‘netustm’) increases, the reported level of happiness (‘happy’) tends to increase slightly.
However, it’s crucial to note that the magnitude of this change is extremely small. The statistical significance of this relationship is not provided in the information you shared. The significance level, often represented by the p-value, would be essential to determine whether this observed relationship is likely to be a real effect or could have occurred by random chance.
# Storing the null distribution
null_distribution <- france_data %>%
specify(explanatory = netustm, response = happy) %>%
hypothesize(null = "independence") %>%
generate(reps = 1000, type = "permute") %>%
calculate(stat = "slope")
## Warning: Removed 14563 rows containing missing values.
# Print the null distribution
print(null_distribution)
## Response: happy (numeric)
## Explanatory: netustm (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.0000395
## 2 2 0.0000535
## 3 3 0.000100
## 4 4 -0.0000395
## 5 5 0.000113
## 6 6 -0.000215
## 7 7 0.0000308
## 8 8 0.0000344
## 9 9 0.0000811
## 10 10 -0.000116
## # ℹ 990 more rows
p_val <- null_distribution %>%
get_pvalue(obs_stat = happy_stat, direction = "two-sided")
p_val
## # A tibble: 1 × 1
## p_value
## <dbl>
## 1 0.95
Interpretation: High p-value (e.g., > 0.05): Fail to reject the null hypothesis.
null_distribution %>%
visualize() +
shade_p_value(obs_stat = happy_stat, direction = "two-sided")
null_distribution
## Response: happy (numeric)
## Explanatory: netustm (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.0000395
## 2 2 0.0000535
## 3 3 0.000100
## 4 4 -0.0000395
## 5 5 0.000113
## 6 6 -0.000215
## 7 7 0.0000308
## 8 8 0.0000344
## 9 9 0.0000811
## 10 10 -0.000116
## # ℹ 990 more rows
Visualizing the null distribution alongside the observed test statistic, we can observe that the red line falls well within the null distribution. This indicates that the observed statistic is not considered unusual or extreme when compared to what would be expected under the null hypothesis. If the observed statistic were to fall within the null distribution, we would expect shaded red regions in the null distribution that are as (or more) extreme than our observed statistic. However, in this case, the observed statistic does not appear to be in an extreme region of the null distribution.
conf_int <- null_distribution %>%
get_confidence_interval(level = 0.95, type = "percentile")
null_distribution %>%
visualize() +
shade_p_value(obs_stat = happy_stat, direction = "two-sided") +
shade_confidence_interval(endpoints = conf_int)
null_distribution
## Response: happy (numeric)
## Explanatory: netustm (numeric)
## Null Hypothesis: independence
## # A tibble: 1,000 × 2
## replicate stat
## <int> <dbl>
## 1 1 0.0000395
## 2 2 0.0000535
## 3 3 0.000100
## 4 4 -0.0000395
## 5 5 0.000113
## 6 6 -0.000215
## 7 7 0.0000308
## 8 8 0.0000344
## 9 9 0.0000811
## 10 10 -0.000116
## # ℹ 990 more rows
It’s also worth mentioning that when the confidence interval (assuming a 95% confidence level) is considered, and it encompasses a range of values that are consistent with the null hypothesis. This further supports the conclusion that, based on the given p-value, we do not have sufficient evidence to reject the null hypothesis.
# Load necessary library
library(mgcv)
## Loading required package: nlme
##
## Attaching package: 'nlme'
## The following object is masked from 'package:dplyr':
##
## collapse
## This is mgcv 1.8-42. For overview type 'help("mgcv-package")'.
france_data <- ess %>%
filter(cntry == "FR") %>%
mutate(
happy = ifelse(happy %in% c(77, 88, 99), NA, happy),
netustm = ifelse(netustm %in% c(6666, 7777, 8888, 9999), NA, netustm),
uemp3m = ifelse(chldhhe %in% c(6, 7, 8, 9), NA, uemp3m)
)
# Convert 'uemp3m' into a factor
france_data$uemp3m <- factor(france_data$uemp3m, levels = c(1, 2), labels = c("Unemployed", "Employed"))
# Fit the linear regression model
model1 <- lm(happy ~ netustm, data = france_data)
model2 <- lm(happy ~ netustm + uemp3m, data = france_data)
model3 <- lm(happy ~ netustm + uemp3m + netustm*uemp3m, data = france_data)
# Generalized Additive Model
model_gam <- gam(happy ~ s(netustm) + uemp3m, data = france_data)
modelsummary(list(model1, model2, model3, model_gam))
| Â (1) | Â Â (2) | Â Â (3) | Â Â (4) | |
|---|---|---|---|---|
| (Intercept) | 7.442 | 7.010 | 7.003 | 7.024 |
| (0.037) | (0.064) | (0.079) | (0.052) | |
| netustm | 0.000 | 0.000 | 0.000 | |
| (0.000) | (0.000) | (0.000) | ||
| uemp3mEmployed | 0.544 | 0.555 | 0.548 | |
| (0.066) | (0.098) | (0.066) | ||
| netustm × uemp3mEmployed | 0.000 | |||
| (0.000) | ||||
| Num.Obs. | 4475 | 2764 | 2764 | 2764 |
| R2 | 0.000 | 0.024 | 0.024 | 0.025 |
| R2 Adj. | 0.000 | 0.024 | 0.023 | |
| AIC | 17218.8 | 10647.4 | 10649.4 | 10648.6 |
| BIC | 17238.0 | 10671.1 | 10679.0 | 10697.5 |
| Log.Lik. | −8606.409 | −5319.694 | −5319.684 | |
| RMSE | 1.66 | 1.66 | 1.66 | 1.66 |
# Fit the linear regression model (assuming this has already been done)
model2 <- lm(happy ~ netustm + uemp3m, data = france_data)
# Extracting coefficients from the model
coefficients <- coef(model2)
# Creating the regression equation
equation <- paste("happy = ",
round(coefficients[1], 3), # Intercept
" + ", round(coefficients[2], 3), "*netustm", # Coefficient for netustm
" + ", round(coefficients[3], 3), "*uemp3mEmployed", # Coefficient for uemp3m (Employed)
sep = "")
# Print the equation
equation
## [1] "happy = 7.01 + 0*netustm + 0.544*uemp3mEmployed"
library(broom)
library(knitr)
# model2 is our regression model
model2 <- lm(happy ~ netustm + uemp3m, data = france_data)
# Use broom to tidy up the model
tidy_model <- tidy(model2)
# Print the coefficients
print(tidy_model)
## # A tibble: 3 × 5
## term estimate std.error statistic p.value
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) 7.01 0.0640 110. 0
## 2 netustm 0.0000920 0.000185 0.496 6.20e- 1
## 3 uemp3mEmployed 0.544 0.0657 8.28 1.88e-16
# Load necessary libraries
library(ggplot2)
library(dplyr)
# Fit the model with interaction term
model3 <- lm(happy ~ netustm * uemp3m, data = france_data)
# Create a new data frame for predictions
prediction_data <- expand.grid(
netustm = seq(min(france_data$netustm, na.rm = TRUE), max(france_data$netustm, na.rm = TRUE), length.out = 100),
uemp3m = c("Unemployed", "Employed")
)
# Predicting happiness scores using the model
prediction_data$predicted_happy <- predict(model3, newdata = prediction_data)
# Plotting
ggplot(prediction_data, aes(x = netustm, y = predicted_happy, color = uemp3m)) +
geom_line() +
labs(title = "Interaction Effect of Internet Usage and Employment Status on Happiness",
x = "Internet Usage (netustm)",
y = "Predicted Happiness (happy)",
color = "Employment Status") +
theme_minimal()