Load libraries and data
library(tidyverse)
library(knitr)
library(gridExtra)
# Helper functions used throughout ------------------------------------------
# p-values: scientific notation when very small, otherwise 3 decimals
fmt_p <- function(p) ifelse(p < 0.001, formatC(p, format = "e", digits = 2),
sprintf("%.3f", p))
# significance stars
stars <- function(p) ifelse(p < 0.001, "***",
ifelse(p < 0.01, "**",
ifelse(p < 0.05, "*", "")))
dataset_url <- "https://raw.githubusercontent.com/miayulia/Sleep-and-Health-Lifestyle-Analysis/main/Sleep_health_and_lifestyle_dataset.csv"
# Try the URL first; if it fails, fall back to a local copy of the CSV
# (download it from Kaggle and put it in the same folder as this file).
sleep_raw <- tryCatch(
read_csv(dataset_url, show_col_types = FALSE),
error = function(e) read_csv("Sleep_health_and_lifestyle_dataset.csv",
show_col_types = FALSE)
)
cat("Rows:", nrow(sleep_raw), " Columns:", ncol(sleep_raw), "\n")
## Rows: 374 Columns: 13
names(sleep_raw)
## [1] "Person ID" "Gender"
## [3] "Age" "Occupation"
## [5] "Sleep Duration" "Quality of Sleep"
## [7] "Physical Activity Level" "Stress Level"
## [9] "BMI Category" "Blood Pressure"
## [11] "Heart Rate" "Daily Steps"
## [13] "Sleep Disorder"
Preprocessing and variable selection (13 to 6 variables)
# Original 13 variables -> keep six core variables and give them short names
sleep <- sleep_raw %>%
mutate(`BMI Category` = ifelse(`BMI Category` == "Normal Weight",
"Normal", `BMI Category`),
`BMI Category` = factor(`BMI Category`,
levels = c("Normal", "Overweight", "Obese"))) %>%
select(Activity = `Physical Activity Level`,
Quality = `Quality of Sleep`,
Duration = `Sleep Duration`,
Stress = `Stress Level`,
Age = Age,
BMI = `BMI Category`)
excluded <- setdiff(names(sleep_raw),
c("Physical Activity Level", "Quality of Sleep",
"Sleep Duration", "Stress Level", "Age", "BMI Category"))
cat("Variables kept (", ncol(sleep), "):", paste(names(sleep), collapse = ", "), "\n")
## Variables kept ( 6 ): Activity, Quality, Duration, Stress, Age, BMI
cat("Variables excluded (", length(excluded), "):", paste(excluded, collapse = ", "), "\n")
## Variables excluded ( 7 ): Person ID, Gender, Occupation, Blood Pressure, Heart Rate, Daily Steps, Sleep Disorder
cat("\nMissing values per kept variable:\n")
##
## Missing values per kept variable:
print(colSums(is.na(sleep)))
## Activity Quality Duration Stress Age BMI
## 0 0 0 0 0 0
cat("\nBMI category counts (after merging 'Normal Weight' into 'Normal'):\n")
##
## BMI category counts (after merging 'Normal Weight' into 'Normal'):
print(table(sleep$BMI))
##
## Normal Overweight Obese
## 216 148 10
Descriptive statistics
var_labels <- c(Activity = "Physical activity (min/day)",
Quality = "Sleep quality (1-10)",
Duration = "Sleep duration (hours)",
Stress = "Stress level (1-10)",
Age = "Age (years)")
table3 <- sleep %>%
select(all_of(names(var_labels))) %>%
pivot_longer(everything(), names_to = "Variable", values_to = "Value") %>%
group_by(Variable) %>%
summarise(N = n(), Mean = mean(Value), SD = sd(Value), Median = median(Value),
Q1 = quantile(Value, 0.25), Q3 = quantile(Value, 0.75),
IQR = IQR(Value), Min = min(Value), Max = max(Value),
.groups = "drop") %>%
arrange(match(Variable, names(var_labels))) %>%
mutate(Variable = unname(var_labels[Variable]),
across(where(is.numeric), ~ round(.x, 2)))
kable(table3, caption = "Table 3. Summary statistics for the quantitative variables (N = 374)")
Table 3. Summary statistics for the quantitative variables (N =
374)
| Physical activity (min/day) |
374 |
59.17 |
20.83 |
60.0 |
45.00 |
75.0 |
30.00 |
30.0 |
90.0 |
| Sleep quality (1-10) |
374 |
7.31 |
1.20 |
7.0 |
6.00 |
8.0 |
2.00 |
4.0 |
9.0 |
| Sleep duration (hours) |
374 |
7.13 |
0.80 |
7.2 |
6.40 |
7.8 |
1.40 |
5.8 |
8.5 |
| Stress level (1-10) |
374 |
5.39 |
1.77 |
5.0 |
4.00 |
7.0 |
3.00 |
3.0 |
8.0 |
| Age (years) |
374 |
42.18 |
8.67 |
43.0 |
35.25 |
50.0 |
14.75 |
27.0 |
59.0 |
Distribution analysis (Figure 1)
Histogram bin widths match the reporting granularity (15 minutes, 1
point, 0.5 hour) so that rounded self-reports do not create artificial
gaps.
p1 <- ggplot(sleep, aes(x = Activity)) +
geom_histogram(binwidth = 15, boundary = 22.5, fill = "blue",
color = "white", alpha = 0.85) +
scale_x_continuous(breaks = seq(30, 90, 15)) +
theme_minimal() +
labs(title = "(a) Daily physical activity",
x = "Activity (min/day)", y = "Frequency")
p2 <- ggplot(sleep, aes(x = Quality)) +
geom_histogram(binwidth = 1, boundary = 3.5, fill = "blue",
color = "white", alpha = 0.85) +
scale_x_continuous(breaks = 4:9) +
theme_minimal() +
labs(title = "(b) Sleep quality rating",
x = "Quality score (1-10)", y = "Frequency")
p3 <- ggplot(sleep, aes(x = Duration)) +
geom_histogram(binwidth = 0.5, boundary = 5.5, closed = "left",
fill = "blue", color = "white", alpha = 0.85) +
scale_x_continuous(breaks = seq(5.5, 8.5, 0.5)) +
theme_minimal() +
labs(title = "(c) Sleep duration",
x = "Sleep duration (hours)", y = "Frequency")
grid.arrange(p1, p2, p3, ncol = 3)
# Evidence for the "rounding" claim: how many records sit on multiples of 15 min?
act_counts <- sort(table(sleep$Activity), decreasing = TRUE)
print(head(act_counts, 8))
##
## 60 30 45 75 90 40 55 35
## 70 68 68 67 67 6 6 4
cat("\nShare of records with activity at a multiple of 15 minutes:",
round(mean(sleep$Activity %% 15 == 0), 3), "\n")
##
## Share of records with activity at a multiple of 15 minutes: 0.909
Correlation analysis (RQ1 and RQ2)
cor_row <- function(x, y, xlab, ylab) {
p <- cor.test(x, y, method = "pearson")
s <- cor.test(x, y, method = "spearman", exact = FALSE)
tibble(Predictor = xlab, Outcome = ylab,
`Pearson r` = round(unname(p$estimate), 3),
`95% CI` = sprintf("[%.3f, %.3f]", p$conf.int[1], p$conf.int[2]),
`p-value` = fmt_p(p$p.value),
`Spearman rho` = round(unname(s$estimate), 3),
`p-value (rho)` = fmt_p(s$p.value))
}
table4 <- bind_rows(
cor_row(sleep$Activity, sleep$Quality, "Physical activity", "Sleep quality"),
cor_row(sleep$Activity, sleep$Duration, "Physical activity", "Sleep duration"),
# Stress rows: these should reproduce r = -0.899 and r = -0.811 quoted in the paper
cor_row(sleep$Stress, sleep$Quality, "Stress level", "Sleep quality"),
cor_row(sleep$Stress, sleep$Duration, "Stress level", "Sleep duration")
)
kable(table4, caption = "Table 4. Correlation between predictors and sleep outcomes (N = 374)")
Table 4. Correlation between predictors and sleep outcomes (N =
374)
| Physical activity |
Sleep quality |
0.193 |
[0.093, 0.289] |
1.75e-04 |
0.178 |
5.25e-04 |
| Physical activity |
Sleep duration |
0.212 |
[0.113, 0.307] |
3.47e-05 |
0.209 |
4.54e-05 |
| Stress level |
Sleep quality |
-0.899 |
[-0.917, -0.877] |
2.88e-135 |
-0.908 |
9.71e-143 |
| Stress level |
Sleep duration |
-0.811 |
[-0.843, -0.773] |
1.24e-88 |
-0.811 |
1.75e-88 |
Simple and multiple linear regression (RQ1, RQ2, RQ3)
# Simple models
mod_q_s <- lm(Quality ~ Activity, data = sleep) # Model 1A
mod_d_s <- lm(Duration ~ Activity, data = sleep) # Model 2A
# Multiple models (BMI reference group = Normal)
mod_q_m <- lm(Quality ~ Activity + Stress + Age + BMI, data = sleep) # Model 1B
mod_d_m <- lm(Duration ~ Activity + Stress + Age + BMI, data = sleep) # Model 2B
models <- list("Model 1A: Quality (simple)" = mod_q_s,
"Model 1B: Quality (multiple)" = mod_q_m,
"Model 2A: Duration (simple)" = mod_d_s,
"Model 2B: Duration (multiple)" = mod_d_m)
term_labels <- c("(Intercept)" = "Intercept (b0)",
"Activity" = "Physical activity (b1)",
"Stress" = "Stress level (b2)",
"Age" = "Age (b3)",
"BMIOverweight" = "BMI: Overweight vs. Normal (b4)",
"BMIObese" = "BMI: Obese vs. Normal (b5)")
coef_cell <- function(m, term) {
s <- summary(m)$coefficients
if (!term %in% rownames(s)) return("-")
sprintf("%.4f (%.4f)%s", s[term, 1], s[term, 2], stars(s[term, 4]))
}
f_pvalue <- function(m) {
f <- summary(m)$fstatistic
pf(f[1], f[2], f[3], lower.tail = FALSE)
}
table5 <- tibble(`Predictor / statistic` = c(unname(term_labels),
"Adjusted R-squared", "F-test p-value"))
for (nm in names(models)) {
m <- models[[nm]]
coefs <- vapply(names(term_labels), function(t) coef_cell(m, t), character(1))
table5[[nm]] <- c(unname(coefs),
sprintf("%.4f", summary(m)$adj.r.squared),
fmt_p(f_pvalue(m)))
}
kable(table5, caption = "Table 5. Simple vs. multiple linear regression models (coefficient (SE); * p < 0.05, ** p < 0.01, *** p < 0.001; N = 374)")
Table 5. Simple vs. multiple linear regression models
(coefficient (SE); * p < 0.05, ** p < 0.01, *** p < 0.001; N =
374)
| Intercept (b0) |
6.6570 (0.1834)*** |
7.5742 (0.1549)*** |
6.6521 (0.1214)*** |
7.3858 (0.1768)*** |
| Physical activity (b1) |
0.0111 (0.0029)*** |
0.0076 (0.0008)*** |
0.0081 (0.0019)*** |
0.0066 (0.0009)*** |
| Stress level (b2) |
- |
-0.4536 (0.0117)*** |
- |
-0.2739 (0.0134)*** |
| Age (b3) |
- |
0.0508 (0.0028)*** |
- |
0.0266 (0.0032)*** |
| BMI: Overweight vs. Normal (b4) |
- |
-0.9732 (0.0458)*** |
- |
-0.7268 (0.0522)*** |
| BMI: Obese vs. Normal (b5) |
- |
-0.9360 (0.1020)*** |
- |
-0.2409 (0.1165)* |
| Adjusted R-squared |
0.0346 |
0.9308 |
0.0425 |
0.7961 |
| F-test p-value |
1.75e-04 |
5.02e-212 |
3.47e-05 |
9.85e-126 |
# Full coefficient tables with p-values and 95% CIs (use these for the [R] values
# in Section 3.5, e.g. the p-value of the activity coefficient in Model 1B)
coef_table <- function(m, title) {
s <- summary(m)$coefficients
ci <- confint(m)
out <- tibble(Term = rownames(s),
Estimate = round(s[, 1], 4),
SE = round(s[, 2], 4),
`95% CI` = sprintf("[%.4f, %.4f]", ci[, 1], ci[, 2]),
`p-value` = fmt_p(s[, 4]))
kable(out, caption = title)
}
coef_table(mod_q_s, "Model 1A (quality, simple)")
Model 1A (quality, simple)
| (Intercept) |
6.6570 |
0.1834 |
[6.2964, 7.0175] |
2.47e-124 |
| Activity |
0.0111 |
0.0029 |
[0.0053, 0.0168] |
1.75e-04 |
coef_table(mod_q_m, "Model 1B (quality, multiple)")
Model 1B (quality, multiple)
| (Intercept) |
7.5742 |
0.1549 |
[7.2695, 7.8789] |
5.04e-163 |
| Activity |
0.0076 |
0.0008 |
[0.0060, 0.0091] |
2.72e-19 |
| Stress |
-0.4536 |
0.0117 |
[-0.4766, -0.4305] |
1.24e-131 |
| Age |
0.0508 |
0.0028 |
[0.0452, 0.0564] |
3.68e-52 |
| BMIOverweight |
-0.9732 |
0.0458 |
[-1.0632, -0.8832] |
5.06e-66 |
| BMIObese |
-0.9360 |
0.1020 |
[-1.1366, -0.7353] |
3.34e-18 |
coef_table(mod_d_s, "Model 2A (duration, simple)")
Model 2A (duration, simple)
| (Intercept) |
6.6521 |
0.1214 |
[6.4135, 6.8908] |
3.10e-180 |
| Activity |
0.0081 |
0.0019 |
[0.0043, 0.0119] |
3.47e-05 |
coef_table(mod_d_m, "Model 2B (duration, multiple)")
Model 2B (duration, multiple)
| (Intercept) |
7.3858 |
0.1768 |
[7.0381, 7.7335] |
1.03e-141 |
| Activity |
0.0066 |
0.0009 |
[0.0049, 0.0084] |
1.79e-12 |
| Stress |
-0.2739 |
0.0134 |
[-0.3002, -0.2475] |
1.23e-62 |
| Age |
0.0266 |
0.0032 |
[0.0202, 0.0330] |
3.27e-15 |
| BMIOverweight |
-0.7268 |
0.0522 |
[-0.8295, -0.6241] |
1.17e-35 |
| BMIObese |
-0.2409 |
0.1165 |
[-0.4699, -0.0119] |
0.039 |
# Check for Table 5: adjusted R-squared of Model 1A should be about 0.0346
# (the draft showed 0.3462, which is inconsistent with its own p-value of 0.00017)
sapply(models, function(m) round(summary(m)$adj.r.squared, 4))
## Model 1A: Quality (simple) Model 1B: Quality (multiple)
## 0.0346 0.9308
## Model 2A: Duration (simple) Model 2B: Duration (multiple)
## 0.0425 0.7961
Interaction models (is the activity-sleep link different at
different stress levels?)
sleep_c <- sleep %>%
mutate(Activity_c = Activity - mean(Activity), # centered to reduce collinearity
Stress_c = Stress - mean(Stress))
mod_q_int <- lm(Quality ~ Activity_c * Stress_c + Age + BMI, data = sleep_c)
mod_d_int <- lm(Duration ~ Activity_c * Stress_c + Age + BMI, data = sleep_c)
int_row <- function(m, label) {
s <- summary(m)$coefficients["Activity_c:Stress_c", ]
tibble(Outcome = label, Estimate = round(s[1], 4), SE = round(s[2], 4),
`p-value` = fmt_p(s[4]))
}
kable(bind_rows(int_row(mod_q_int, "Sleep quality"),
int_row(mod_d_int, "Sleep duration")),
caption = "Activity x Stress interaction term (centered predictors)")
Activity x Stress interaction term (centered
predictors)
| Sleep quality |
-0.0023 |
4e-04 |
1.17e-08 |
| Sleep duration |
-0.0006 |
5e-04 |
0.196 |
Group comparisons by BMI category (RQ3) - Tables 6, 7, 8
table6 <- sleep %>%
group_by(BMI) %>%
summarise(n = n(),
`Sleep quality, mean (SD)` = sprintf("%.2f (%.2f)", mean(Quality), sd(Quality)),
`Sleep duration, mean (SD)` = sprintf("%.2f (%.2f)", mean(Duration), sd(Duration)),
.groups = "drop") %>%
rename(`BMI category` = BMI)
kable(table6, caption = "Table 6. Sleep outcomes by BMI category")
Table 6. Sleep outcomes by BMI category
| Normal |
216 |
7.64 (1.00) |
7.39 (0.72) |
| Overweight |
148 |
6.90 (1.25) |
6.77 (0.76) |
| Obese |
10 |
6.40 (1.90) |
6.96 (0.88) |
bmi_tests <- function(var, label) {
f <- as.formula(paste(var, "~ BMI"))
a <- aov(f, data = sleep)
s <- summary(a)[[1]]
k <- kruskal.test(f, data = sleep)
tk <- TukeyHSD(a)$BMI
pw <- pairwise.wilcox.test(sleep[[var]], sleep$BMI,
p.adjust.method = "holm", exact = FALSE)$p.value
pairs <- c("Overweight-Normal", "Obese-Normal", "Obese-Overweight")
t7 <- tibble(Outcome = label,
Test = c("One-way ANOVA", "Kruskal-Wallis"),
`Test statistic` = c(sprintf("F = %.2f", s[["F value"]][1]),
sprintf("chi-sq = %.3f", unname(k$statistic))),
df = c(paste(s[["Df"]][1], s[["Df"]][2], sep = ", "),
as.character(unname(k$parameter))),
`p-value` = c(fmt_p(s[["Pr(>F)"]][1]), fmt_p(k$p.value)))
t8 <- tibble(Outcome = label,
Comparison = c("Overweight - Normal", "Obese - Normal",
"Obese - Overweight"),
`Mean difference` = round(unname(tk[pairs, "diff"]), 3),
`Tukey adjusted p` = fmt_p(unname(tk[pairs, "p adj"])),
`Wilcoxon (Holm) p` = fmt_p(c(pw["Overweight", "Normal"],
pw["Obese", "Normal"],
pw["Obese", "Overweight"])))
list(t7 = t7, t8 = t8)
}
res_q <- bmi_tests("Quality", "Sleep quality")
res_d <- bmi_tests("Duration", "Sleep duration")
kable(bind_rows(res_q$t7, res_d$t7),
caption = "Table 7. Tests of differences in sleep outcomes across BMI categories")
Table 7. Tests of differences in sleep outcomes across BMI
categories
| Sleep quality |
One-way ANOVA |
F = 22.01 |
2, 371 |
9.26e-10 |
| Sleep quality |
Kruskal-Wallis |
chi-sq = 37.895 |
2 |
5.90e-09 |
| Sleep duration |
One-way ANOVA |
F = 31.00 |
2, 371 |
3.55e-13 |
| Sleep duration |
Kruskal-Wallis |
chi-sq = 43.070 |
2 |
4.44e-10 |
kable(bind_rows(res_q$t8, res_d$t8),
caption = "Table 8. Pairwise comparisons between BMI categories")
Table 8. Pairwise comparisons between BMI categories
| Sleep quality |
Overweight - Normal |
-0.740 |
7.40e-09 |
6.66e-09 |
| Sleep quality |
Obese - Normal |
-1.239 |
0.002 |
0.039 |
| Sleep quality |
Obese - Overweight |
-0.499 |
0.371 |
0.672 |
| Sleep duration |
Overweight - Normal |
-0.618 |
0.00e+00 |
1.53e-10 |
| Sleep duration |
Obese - Normal |
-0.428 |
0.174 |
0.342 |
| Sleep duration |
Obese - Overweight |
0.190 |
0.712 |
0.818 |
# Variance inflation factors (values above about 5 suggest collinearity problems)
vif_tbl <- function(m) {
X <- model.matrix(m)[, -1, drop = FALSE]
v <- diag(solve(cor(X)))
tibble(Term = names(v), VIF = round(unname(v), 2))
}
kable(vif_tbl(mod_q_m), caption = "Variance inflation factors for the multiple models (same predictors in 1B and 2B)")
Variance inflation factors for the multiple models (same
predictors in 1B and 2B)
| Activity |
1.04 |
| Stress |
1.63 |
| Age |
2.27 |
| BMIOverweight |
1.89 |
| BMIObese |
1.02 |
#Alternative handling of rounded activity values: Low / Moderate /
High groups
sleep_grp <- sleep %>%
mutate(ActivityGroup = cut(Activity, breaks = c(-Inf, 44, 60, Inf),
labels = c("Low (<45 min)", "Moderate (45-60 min)",
"High (>60 min)")))
kable(sleep_grp %>%
group_by(ActivityGroup) %>%
summarise(n = n(),
`Quality, mean (SD)` = sprintf("%.2f (%.2f)", mean(Quality), sd(Quality)),
`Duration, mean (SD)` = sprintf("%.2f (%.2f)", mean(Duration), sd(Duration)),
.groups = "drop"),
caption = "Sleep outcomes by activity group")
Sleep outcomes by activity group
| Low (<45 min) |
82 |
7.01 (1.70) |
7.04 (1.13) |
| Moderate (45-60 min) |
149 |
7.21 (0.83) |
6.87 (0.39) |
| High (>60 min) |
143 |
7.59 (1.12) |
7.46 (0.77) |
kruskal.test(Quality ~ ActivityGroup, data = sleep_grp)
##
## Kruskal-Wallis rank sum test
##
## data: Quality by ActivityGroup
## Kruskal-Wallis chi-squared = 11.309, df = 2, p-value = 0.003502
kruskal.test(Duration ~ ActivityGroup, data = sleep_grp)
##
## Kruskal-Wallis rank sum test
##
## data: Duration by ActivityGroup
## Kruskal-Wallis chi-squared = 39.764, df = 2, p-value = 2.319e-09