REGRESSION MODELLING FOR HEALTH PRACTITIONERS · CHAPTER 16
Implementation in R, Python and Julia
Health practitioners increasingly use programming languages to analyse data and fit regression models. This chapter summarises common packages and illustrates how to implement key models across R, Python and Julia.
Key Packages
R: The base
statspackage provideslmfor linear regression andglmfor generalised linear models. Thesurvivalpackage implements Cox models and Kaplan–Meier curves.lme4andnlmefit mixed effects models.mgcvandsplinesprovide smoothing and GAMs.miceperforms multiple imputation;glmnetfits penalised regression;caretfacilitates cross‑validation;tidyverseaids data wrangling.Python: The
scikit_learnlibrary implements linear, logistic, Poisson and regularised regression, K‑fold cross‑validation and pipelines.statsmodelsprovides a formula interface for ordinary least squares, generalised linear models and survival models.lifelinesimplements survival analysis.patsybuilds design matrices.pyGAMfits generalised additive models.sklearn.imputehandles missing data.Julia:
DataFrames.jlandCSV.jlprovide data structures and import.GLM.jlfits linear and generalised linear models via a formula interface.MixedModels.jlimplements mixed effects models.Survival.jlprovides survival functions.Impute.jlperforms simple imputation.Lasso.jlandMLJ.jlimplement penalised regression and machine learning workflows. Smoothing can be performed usingInterpolations.jlor via interfacing with R.
Example: Logistic Regression Across Languages
We illustrate fitting a logistic regression model to predict disease status from age and biomarker level.
Worked example
R:
data <- read.csv("example.csv")
fit <- glm(Disease ~ Age + Biomarker, family = binomial(), data = data)
summary(fit)
Python:
import pandas as pd
import statsmodels.api as sm
df = pd.read_csv("example.csv")
X = sm.add_constant(df[["Age", "Biomarker"]])
y = df["Disease"]
model = sm.Logit(y, X).fit()
print(model.summary())
Julia:
using CSV, DataFrames, GLM
df = CSV.read("example.csv", DataFrame)
model = glm(@formula(Disease ~ Age + Biomarker), df, Binomial(), LogitLink())
coeftable(model)
Cross‑Validation Example
Worked example
R: using caret
library(caret)
ctrl <- trainControl(method = "cv", number = 5)
fit_cv <- train(Disease ~ Age + Biomarker, data = data,
method = "glm", family = binomial(), trControl = ctrl)
print(fit_cv)
Python: using scikit_learn
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
scores = cross_val_score(LogisticRegression(max_iter=1000), X, y, cv=5)
print(scores.mean())
Julia: using MLJ
using MLJ
logit_model = @load LogisticClassifier pkg = GLM
mach = machine(logit_model, X, y)
cv = CV(nfolds = 5, shuffle = true)
res = evaluate!(mach, resampling = cv, measure = auc)
println(res.measurement)
Tips for Reproducibility
Use set seeds (e.g.,
set.seedin R,random_statein Python) to ensure reproducible results.Document package versions using tools like
sessionInfo()in R orpip freezein Python.Keep scripts organised and use literate programming tools (e.g., R Markdown, Jupyter notebooks) to combine code, narrative and output.
Exercises
Fit a mixed effects model in R, Python or Julia for a dataset with repeated measurements (random intercept for subject). Compare results across languages.
Implement Poisson regression with an offset term in each language and compare rate ratios.
Fit a generalised additive model (GAM) for a continuous outcome with a smooth function of age using
mgcvin R,pyGAMin Python and an appropriate tool in Julia.Explore how different cross‑validation folds affect the estimated performance of a logistic regression model.
Code examples use illustrative datasets. Supply data with the named columns to run them.