regression_report.R in R
Fit a multiple regression and print a tidy coefficient table.
#!/usr/bin/env Rscript
# Fit a linear model on mtcars and print a tidy summary.
fit_model <- function(data) {
lm(mpg ~ wt + hp + factor(cyl), data = data)
}
print_coefficients <- function(model) {
coefs <- summary(model)$coefficients
cat(sprintf("%-18s %9s %9s %9s\n",
"term", "estimate", "std.error", "p.value"))
for (term in rownames(coefs)) {
cat(sprintf("%-18s %9.3f %9.3f %9.4f\n",
term, coefs[term, 1], coefs[term, 2], coefs[term, 4]))
}
}
model <- fit_model(mtcars)
print_coefficients(model)
cat("\nr.squared: ", round(summary(model)$r.squared, 4), "\n")
cat("adj.r.squared:", round(summary(model)$adj.r.squared, 4), "\n")
cat("rmse: ", round(sqrt(mean(resid(model)^2)), 4), "\n")
cat("aic: ", round(AIC(model), 2), "\n")
How it works
- The formula mixes numeric predictors with a factor.
summary(model)$coefficientsdrives a formatted table.- R-squared, RMSE, and AIC summarize the fit.
Keywords and builtins used here
AICcatfactorfit_modelforfunctioninlmmeanprint_coefficientsresidroundrownamessprintfsqrtsummary
The run, in numbers
- Lines
- 24
- Characters to type
- 752
- Tokens
- 199
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 114 seconds.
Step 1 of 2 in Encore, step 10 of 11 in Statistics.