clinical-trials
Clinical trial design and analysis methods in R, including randomization, estimands, multiplicity, and reporting.
What this skill does
# Clinical Trials Statistical Methods
## Overview
Comprehensive clinical trial design and analysis methods in R covering sample size calculation, randomization, interim analyses, multiplicity adjustment, and regulatory-compliant statistical methods.
## Sample Size Calculation
### Two-Group Comparisons
```r
library(pwr)
# Two-sample t-test
pwr.t.test(
d = 0.5, # Cohen's d effect size
sig.level = 0.05,
power = 0.80,
type = "two.sample",
alternative = "two.sided"
)
# Proportions (chi-square)
pwr.2p.test(
h = ES.h(p1 = 0.6, p2 = 0.4), # Cohen's h
sig.level = 0.05,
power = 0.80
)
# Two proportions (unequal groups)
pwr.2p2n.test(
h = ES.h(p1 = 0.6, p2 = 0.4),
n1 = 100,
sig.level = 0.05
)
```
### Survival Endpoints
```r
library(gsDesign)
# Log-rank test sample size
nSurv(
lambda1 = log(2)/12, # Control median = 12 months
lambda2 = log(2)/18, # Treatment median = 18 months (HR = 0.67)
Ts = 24, # Study duration
Tr = 12, # Accrual duration
alpha = 0.025, # One-sided
beta = 0.20, # 80% power
ratio = 1 # 1:1 randomization
)
# Using rpact
library(rpact)
getSampleSizeSurvival(
hazardRatio = 0.67,
lambda1 = log(2)/12,
accrualTime = 12,
followUpTime = 12,
alpha = 0.025,
beta = 0.20,
allocationRatioPlanned = 1
)
```
### Non-Inferiority Trials
```r
library(TrialSize)
# Non-inferiority for proportions
TwoSampleProportion.NIS(
p = 0.80, # Expected proportion in both groups
delta = 0.10, # Non-inferiority margin
alpha = 0.025, # One-sided
power = 0.80
)
# Non-inferiority for means
TwoSampleMean.NIS(
sigma = 10, # SD
delta = 5, # Non-inferiority margin
alpha = 0.025,
power = 0.80
)
```
## Randomization
### Simple Randomization
```r
# Base R simple randomization
set.seed(123)
n <- 100
treatment <- sample(c("A", "B"), n, replace = TRUE)
# blockrand package
library(blockrand)
randomization <- blockrand(
n = 100,
num.levels = 2,
levels = c("Treatment", "Control"),
id.prefix = "PAT",
block.prefix = "BLK"
)
```
### Stratified Block Randomization
```r
library(blockrand)
# Generate lists for each stratum
strata <- expand.grid(
sex = c("Male", "Female"),
age_group = c("<65", ">=65")
)
rand_lists <- lapply(1:nrow(strata), function(i) {
blockrand(
n = 50,
num.levels = 2,
levels = c("Treatment", "Control"),
block.sizes = c(2, 4, 6), # Variable block sizes
stratum = paste(strata[i, ], collapse = "_")
)
})
full_list <- do.call(rbind, rand_lists)
```
### Minimization
```r
library(Minirand)
# Minimization randomization
minirand(
covariates = data.frame(
sex = c("M", "F", "M"),
age = c("young", "old", "young"),
center = c("A", "A", "B")
),
treatment = c("A", "B"),
ratio = c(1, 1),
p = 0.85 # Probability of assigning to minimizing treatment
)
```
## Baseline Characteristics
For randomized trials, baseline tables should primarily describe the randomized groups and assess clinically meaningful imbalance. Routine baseline hypothesis tests are usually not appropriate because any baseline differences arise after randomization and p-values mostly reflect sample size.
```r
library(gtsummary)
baseline_table <- adsl |>
dplyr::filter(ITTFL == "Y") |>
dplyr::select(TRT01P, AGE, SEX, BMI, BASELINE_SCORE) |>
tbl_summary(
by = TRT01P,
statistic = list(
all_continuous() ~ "{mean} ({sd})",
all_categorical() ~ "{n} ({p}%)"
)
) |>
modify_header(label = "**Characteristic**")
```
If the SAP requires standardized mean differences, report them as descriptive diagnostics rather than randomization tests.
## Group Sequential Designs
### gsDesign Package
```r
library(gsDesign)
# O'Brien-Fleming boundaries
gs_design <- gsDesign(
k = 3, # Number of analyses
test.type = 2, # Two-sided symmetric
alpha = 0.025, # One-sided alpha
beta = 0.20, # Type II error
sfu = "OF", # O'Brien-Fleming spending function
timing = c(0.5, 0.75, 1) # Information fractions
)
# Summary
gs_design
# Boundaries
gs_design$upper$bound # Upper efficacy boundary
gs_design$lower$bound # Lower futility boundary
# Plot
plot(gs_design)
```
### Alpha Spending Functions
```r
# Pocock
gs_pocock <- gsDesign(k = 3, sfu = "Pocock")
# Hwang-Shih-DeCani
gs_hsd <- gsDesign(k = 3, sfu = sfHSD, sfupar = -4)
# Power family (Kim-DeMets)
gs_power <- gsDesign(k = 3, sfu = sfPower, sfupar = 2)
# Custom spending
gs_custom <- gsDesign(
k = 3,
sfu = sfPoints,
sfupar = c(0.01, 0.03, 0.025), # Cumulative alpha at each look
timing = c(0.5, 0.75, 1)
)
```
### rpact Package
```r
library(rpact)
# Design
design <- getDesignGroupSequential(
kMax = 3,
alpha = 0.025,
beta = 0.20,
sided = 1,
typeOfDesign = "OF", # O'Brien-Fleming
informationRates = c(0.5, 0.75, 1)
)
# Sample size
sampleSize <- getSampleSizeMeans(
design = design,
alternative = 0.5,
stDev = 1
)
# Interim analysis
getAnalysisResults(
design,
dataInput = getDataset(
n = c(50, 75),
means = c(0.3, 0.4),
stDevs = c(1, 1)
)
)
```
## Multiplicity Adjustment
### P-value Adjustments
```r
# Bonferroni
p.adjust(p_values, method = "bonferroni")
# Holm (step-down)
p.adjust(p_values, method = "holm")
# Hochberg (step-up)
p.adjust(p_values, method = "hochberg")
# Benjamini-Hochberg (FDR)
p.adjust(p_values, method = "BH")
# Hommel
p.adjust(p_values, method = "hommel")
```
### Graphical Approaches
```r
library(gMCP)
# Define hypothesis graph
graph <- matrix2graph(
# Transition matrix
m = matrix(c(
0, 0.5, 0.5, 0,
0.5, 0, 0, 0.5,
0.5, 0, 0, 0.5,
0, 0.5, 0.5, 0
), nrow = 4, byrow = TRUE),
# Initial weights
w = c(0.5, 0.5, 0, 0)
)
# Set hypothesis names
nodeNames(graph) <- c("H1_OS", "H2_OS", "H1_PFS", "H2_PFS")
# Plot graph
plot(graph)
# Perform test
gMCP(
graph = graph,
pvalues = c(0.01, 0.03, 0.02, 0.04),
alpha = 0.025
)
```
### Gatekeeping Procedures
```r
library(multcomp)
# Serial gatekeeping
# Primary must be significant before testing secondary
serial_gate <- function(p_primary, p_secondary, alpha = 0.05) {
if (p_primary < alpha) {
# Primary significant, test secondary at full alpha
return(c(primary = p_primary < alpha, secondary = p_secondary < alpha))
} else {
return(c(primary = FALSE, secondary = FALSE))
}
}
```
## Missing Data
### Mixed Models for Repeated Measures (MMRM)
```r
library(mmrm)
# MMRM model
mmrm_fit <- mmrm(
formula = change ~ treatment * visit + baseline + us(visit | subject),
data = long_data,
weights = NULL,
reml = TRUE
)
# Least squares means
library(emmeans)
emmeans(mmrm_fit, ~ treatment | visit)
# Treatment comparison at each visit
emmeans(mmrm_fit, pairwise ~ treatment | visit)
```
### Multiple Imputation
```r
library(mice)
# Create imputations
imp <- mice(
data = df,
m = 20, # Number of imputations
method = "pmm", # Predictive mean matching
maxit = 10
)
# Analyze each imputed dataset
analyses <- with(imp, lm(outcome ~ treatment + covariates))
# Pool results (Rubin's rules)
pooled <- pool(analyses)
summary(pooled)
```
### Tipping Point Analysis
```r
# Sensitivity analysis for MNAR
library(rbmi)
# Define imputation method with delta adjustment
draws <- draws(
data = data,
data_ice = ice_data,
method = method_bayes(),
vars = vars
)
# Impute with different delta values
impute(draws, references = c("Control" = "Control", "Treatment" = "Control"))
```
## Subgroup Analysis
### Forest Plots for Subgroups
```r
library(forestplot)
# Calculate treatment effects by subgroup
subgroup_effects <- df |>
group_by(subgroup) |>
summarise(
n = n(),
effect = mean(outcome[trt == 1]) - mean(outcome[trt == 0]),
se = sqrt(var(outcome[trt == 1])/sum(trt == 1) +
var(outcome[trt == 0])/sum(trt == 0)),
lower = effect - 1.96 * se,
upper = effect + 1.96 * se
)Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.