# Compare test RMSPE for models with 1–6 predictors (forward order)
set.seed(42)
k <- 10
folds <- sample(rep(1:k, length.out = nrow(nhanes_cc)))
predictor_sets <- list(
"Age only" = "SBP ~ Age",
"Age + Sex" = "SBP ~ Age + Sex",
"Age + Sex + BMI" = "SBP ~ Age + Sex + BMI",
"Age + Sex + BMI + Waist" = "SBP ~ Age + Sex + BMI + Waist",
"Age + Sex + BMI + Waist + Chol" = "SBP ~ Age + Sex + BMI + Waist + Cholesterol",
"Full model" = "SBP ~ Age + Sex + BMI + Waist + Cholesterol + factor(Diabetes) + factor(Smoker)"
)
cv_rmspe <- sapply(predictor_sets, function(fmla) {
sqrt(mean(sapply(1:k, function(j) {
tr <- nhanes_cc[folds != j, ]
te <- nhanes_cc[folds == j, ]
fit <- lm(as.formula(fmla), data = tr)
mean((te$SBP - predict(fit, newdata = te))^2, na.rm = TRUE)
})))
})
res <- data.frame(Model = factor(names(cv_rmspe), levels = names(cv_rmspe)),
RMSPE = cv_rmspe)
ggplot(res, aes(x = Model, y = RMSPE)) +
geom_col(fill = "#2980b9", alpha = 0.8) +
geom_text(aes(label = round(RMSPE, 2)), vjust = -0.4, size = 3.5) +
labs(title = "10-fold CV RMSPE by model size (NHANES, outcome = SBP)",
x = NULL, y = "RMSPE (mmHg)") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 25, hjust = 1))