Ready-to-run R code for common clinical analyses. Click any template to open it in the console.
Descriptive statistics, str(), table() and tapply() on a simulated clinical dataset.
# Descriptive statistics on a simulated clinical dataset
data <- data.frame(
subjid = paste0("SUBJ-", 1:8),
age = c(45, 52, 38, 61, 47, 55, 42, 49),
bmi = c(24.1, 28.3, 22.7, 31.4, 26.8, 29.1, 23.5, 27.6),
bp_sys = c(120, 145, 118, 152, 128, 138, 122, 135),
group = c("A","A","B","B","A","B","A","B")
)
…Kaplan-Meier survival curves with median survival table. Installs the survival package on first run.
# Kaplan-Meier survival analysis
# NOTE: installs the 'survival' package on first run (~30s)
webr::install("survival")
library(survival)
set.seed(42)
n <- 60
surv_data <- data.frame(
…Welch t-test comparing treatment arms, with effect size (Cohen's d) and a box plot.
# Comparing treatment arms — change from baseline
set.seed(123)
trt <- rnorm(30, mean = -5.2, sd = 3.1)
ctrl <- rnorm(30, mean = -1.8, sd = 3.4)
cat("=== Descriptive Statistics ===\n")
stats <- data.frame(
Group = c("Treatment", "Control"),
…Analysis of covariance — treatment effect adjusted for baseline, with LS-means and scatter plot.
# ANCOVA: treatment effect adjusted for baseline
set.seed(77)
n <- 40
df <- data.frame(
baseline = rnorm(n, 130, 15),
trt = rep(c("Drug", "Placebo"), each = n/2)
)
df$endpoint <- df$baseline - ifelse(df$trt == "Drug", 12, 2) + rnorm(n, 0, 8)
…Pairwise Pearson correlations for clinical lab values with significance testing and pairs plot.
# Correlation matrix for clinical lab values
set.seed(99)
n <- 50
lab <- data.frame(
age = round(rnorm(n, 55, 10)),
bmi = round(rnorm(n, 27, 4), 1),
sbp = round(rnorm(n, 130, 15)),
dbp = round(rnorm(n, 82, 10)),
…Histogram with normal curve overlay and reference lines — useful for lab value distributions.
# Lab value distribution with reference ranges
set.seed(7)
hgb <- c(rnorm(60, mean = 13.8, sd = 1.2),
rnorm(15, mean = 9.5, sd = 1.0))
hist(hgb,
breaks = 20,
freq = FALSE,
…Side-by-side box plots with jittered data points comparing treatment groups.
# Systolic BP by dose group
set.seed(21)
n <- 25
bp <- data.frame(
value = c(rnorm(n, 132, 12), rnorm(n, 122, 10), rnorm(n, 115, 11)),
group = factor(
rep(c("Placebo", "Low Dose (5mg)", "High Dose (10mg)"), each = n),
levels = c("Placebo", "Low Dose (5mg)", "High Dose (10mg)")
…Manual forest plot for subgroup hazard ratios — common in clinical study reports.
# Forest plot for subgroup analysis
subgroups <- c("Overall", "Age < 65", "Age >= 65",
"Male", "Female",
"Low Baseline", "High Baseline")
hr <- c(0.72, 0.68, 0.78, 0.70, 0.74, 0.65, 0.80)
lower <- c(0.58, 0.51, 0.57, 0.53, 0.55, 0.47, 0.59)
upper <- c(0.89, 0.91, 1.07, 0.93, 1.00, 0.90, 1.09)
n_trt <- c(120, 55, 65, 70, 50, 58, 62)
…Have a clinical R template to share? Submit it for review
