Book contents

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

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

Exercises

  1. Fit a mixed effects model in R, Python or Julia for a dataset with repeated measurements (random intercept for subject). Compare results across languages.

  2. Implement Poisson regression with an offset term in each language and compare rate ratios.

  3. Fit a generalised additive model (GAM) for a continuous outcome with a smooth function of age using mgcv in R, pyGAM in Python and an appropriate tool in Julia.

  4. 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.