
Planning a Study: Power and Sample Size by Simulation
Source:vignettes/articles/planning-a-study.Rmd
planning-a-study.RmdBefore a trial starts, someone has to answer “how many subjects do we need?” The textbook formulas answer it for a two-sample t-test or a two-proportion z-test. The trial you are planning may use a covariate-balancing design, a covariate-adjusted analysis, a binary or survival outcome, or subjects who arrive one at a time. No closed-form formula covers that combination. A simulation does: generate the trial many times with a treatment effect you plant, run the analysis you will actually run, and count how often it rejects.
This article walks through that workflow with EDI (Experimental Design and Inference). It assumes you know the four steps of an EDI analysis (design, assign, record responses, infer) from Get started or the continuous cookbook. If you have never computed power by simulation, Lesson 3 of Learn Statistics Through EDI does it for a plain t-test first.
The recipe
-
Fix what the trial will do. The design (how
treatment is assigned), the analysis (an inference class and a
procedure, such as its Wald test), and the significance level
alpha. - Fix what you believe about the world. An outcome model: how the covariates you will record relate to the outcome, how noisy the outcome is, and how the covariates are distributed in the population you will enroll. Then the effect size you want to detect, on the scale the analysis reports.
-
Simulate. For each candidate sample size
n, simulateRtrials. In each, drawnsubjects, assign treatment with the design, generate outcomes with the planted effect, run the analysis, and record whetherp < alpha. -
Read off power. Power at
nis the rejection rate. Pick the smallestnwhose lower Monte Carlo bound clears your target (80% below). Using the lower bound rather than the point estimate guards against picking annthat only looks adequate because of simulation noise. -
Check size. Rerun at the chosen
nwith the effect set to zero. If the procedure rejects much more thanalphaof the time there, its power at thatnmeans nothing (see Checking size too).
A rejection rate estimated from R trials has Monte Carlo
standard error \(\sqrt{p(1-p)/R}\).
Near the target \(p = 0.8\), the number
of trials needed for a 95% interval of half-width \(h\) is \(R =
1.96^2 \times 0.8 \times 0.2 / h^2\):
h = c(0.05, 0.04, 0.03, 0.02, 0.01)
data.frame(half_width = h, R_needed = ceiling(qnorm(0.975)^2 * 0.8 * 0.2 / h^2))
#> half_width R_needed
#> 1 0.05 246
#> 2 0.04 385
#> 3 0.03 683
#> 4 0.02 1537
#> 5 0.01 6147This article uses R = 250 to 500 per power point so that
it builds in a few minutes, which gives a half-width of 4 to 5
percentage points. For a real protocol, use 1,500 or more at the final
n.
Two small helpers turn rejection rates into intervals and pick the
n:
alpha = 0.05
target_power = 0.80
mc_bounds = function(p, R) {
h = qnorm(0.975) * sqrt(p * (1 - p) / R)
data.frame(lower = pmax(p - h, 0), upper = pmin(p + h, 1))
}
smallest_n = function(n, power, R, target = target_power) {
ok = which(mc_bounds(power, R)$lower >= target)
if (length(ok) == 0) NA else n[min(ok)]
}Worked example 1: a continuous outcome, two designs
The question. A trial will record two baseline
covariates and a continuous outcome. How many subjects are needed for
80% power to detect a treatment effect of 0.9 outcome units at
alpha = 0.05, under complete randomization versus pairwise
matching on the covariates?
The outcome model. The covariates are standard normal. The outcome depends on them partly linearly and partly not, with residual noise of standard deviation 1:
draw_covariates = function(n) data.frame(x1 = rnorm(n), x2 = rnorm(n))
outcome_model = function(X) X$x1 + 0.5 * X$x2 + 0.8 * (X$x1^2 - 1) + 0.6 * X$x1 * X$x2
beta1 = 0.9 # the treatment effect to detect, in outcome unitsThe designs and analyses.
-
DesignFixediBCRD: complete randomization with equal arms, analyzed withInferenceContinOLS(regression on treatment and the covariates). -
DesignFixedBinaryMatch: subjects are paired on Mahalanobis distance and one of each pair is treated. Analyzed two ways: with the sameInferenceContinOLS, and withInferenceContinKKOLSOneLik, the matched analysis, which fits one covariate-adjusted regression over the within-pair differences (and any unmatched subjects).
With SimulationFramework
SimulationFramework
fits this job well. It takes vectors of sample sizes n and
effects betaT, runs every design against every inference
class (skipping combinations that do not apply, such as the matched
analysis on a design that does not match), and reports power per cell.
Its built-in outcome model is linear in the covariates. To use your own,
pass custom_replication_data_generator, a function of
(state, rep) that returns the covariates X and
the control-arm mean y_linear_model for
state$n subjects. For a continuous outcome the framework
then adds betaT to treated subjects and normal noise with
standard deviation sd_noise.
inference_types_and_params = list(asymp_pval = list())
limits each analysis to its asymptotic p-value, the fast choice for
screening sample sizes. seed gives every replication its
own seed (seed + i), so the run is reproducible whatever
num_cores is (see Reproducibility).
ns1 = c(30L, 50L, 70L, 90L, 120L, 150L)
R1 = 250L
generator = function(state, rep) {
X = draw_covariates(state$n)
list(X = X, y_linear_model = outcome_model(X))
}
sim1 = SimulationFramework$new(
response_type = "continuous",
design_classes_and_params = list(DesignFixediBCRD = list(), DesignFixedBinaryMatch = list()),
inference_classes_and_params = list(InferenceContinOLS = list(), InferenceContinKKOLSOneLik = list()),
n = ns1, p = 2L, betaT = beta1, sd_noise = 1, alpha = alpha, Nrep_W = R1,
custom_replication_data_generator = generator,
inference_types_and_params = list(asymp_pval = list()),
results_filename = tempfile(fileext = ".csv"), continue_from_last_result_row = FALSE,
seed = 2026L, num_cores = 2L, verbose = FALSE
)
sim1$run()
pow1 = as.data.frame(SimulationFrameworkReport$new(sim1)$summarize())
pow1$analysis = paste(sub("^Design", "", pow1$design), "+", sub("^Inference", "", pow1$inference))
pow1 = cbind(pow1, mc_bounds(pow1$power, pow1$n_pow))
pow1[, c("n", "analysis", "power", "lower", "upper", "n_pow")]
#> n analysis power lower upper n_pow
#> 1 30 FixedBinaryMatch + ContinKKOLSOneLik 0.464 0.4021814 0.5258186 250
#> 2 30 FixedBinaryMatch + ContinOLS 0.372 0.3120859 0.4319141 250
#> 3 30 FixediBCRD + ContinOLS 0.320 0.2621761 0.3778239 250
#> 4 50 FixedBinaryMatch + ContinKKOLSOneLik 0.752 0.6984681 0.8055319 250
#> 5 50 FixedBinaryMatch + ContinOLS 0.536 0.4741814 0.5978186 250
#> 6 50 FixediBCRD + ContinOLS 0.524 0.4620919 0.5859081 250
#> 7 70 FixedBinaryMatch + ContinKKOLSOneLik 0.912 0.8768830 0.9471170 250
#> 8 70 FixedBinaryMatch + ContinOLS 0.724 0.6685882 0.7794118 250
#> 9 70 FixediBCRD + ContinOLS 0.704 0.6474138 0.7605862 250
#> 10 90 FixedBinaryMatch + ContinKKOLSOneLik 0.932 0.9007938 0.9632062 250
#> 11 90 FixedBinaryMatch + ContinOLS 0.836 0.7901010 0.8818990 250
#> 12 90 FixediBCRD + ContinOLS 0.724 0.6685882 0.7794118 250
#> 13 120 FixedBinaryMatch + ContinKKOLSOneLik 0.976 0.9570282 0.9949718 250
#> 14 120 FixedBinaryMatch + ContinOLS 0.904 0.8674828 0.9405172 250
#> 15 120 FixediBCRD + ContinOLS 0.836 0.7901010 0.8818990 250
#> 16 150 FixedBinaryMatch + ContinKKOLSOneLik 0.996 0.9881758 1.0000000 250
#> 17 150 FixedBinaryMatch + ContinOLS 0.964 0.9409077 0.9870923 250
#> 18 150 FixediBCRD + ContinOLS 0.924 0.8911511 0.9568489 250
analyses1 = c(crd = "FixediBCRD + ContinOLS",
m_ols = "FixedBinaryMatch + ContinOLS",
m_kk = "FixedBinaryMatch + ContinKKOLSOneLik")
curve1 = lapply(analyses1, function(a) pow1[pow1$analysis == a, ][order(pow1$n[pow1$analysis == a]), ])
n_pick1 = sapply(curve1, function(d) smallest_n(d$n, d$power, d$n_pow))
n_pick1
#> crd m_ols m_kk
#> 150 120 70
power_at = function(curve, n) curve$power[curve$n == n]
The bars are 95% Monte Carlo intervals from 250 simulated trials per
point, and the dotted line is the 80% target. The smallest
n on the grid whose lower bound clears 80% is:
- complete randomization with OLS: n = 150 (power 92.4%);
- matched pairs with the matched analysis: n = 70 (power 91.2%);
- matched pairs analyzed with plain OLS: n = 120.
These are provisional until the size check in Checking size too.
So under this outcome model the matched design needs about 53% fewer subjects than complete randomization, for the same analysis goal. The design changed the sample size, but only together with an analysis that uses the pairs. Plain OLS on the matched design estimates the effect just as precisely as the matched analysis (its mean squared error at n = 150 was 0.032 versus 0.034 for the matched analysis and 0.072 under complete randomization), but its standard error does not know about the matching, so it overstates the uncertainty and gives up part of the gain.
The gain depends on the outcome model. Here the covariates act on the
outcome partly through a square and an interaction, which pairing on the
covariates balances and linear adjustment does not remove. If the
outcome were linear in the covariates, OLS adjustment alone would remove
most of what matching removes, and the two designs would need similar
sample sizes. That is why the outcome model is part of the plan: change
outcome_model to function(X) X$x1 + 0.5 * X$x2
and rerun to see it.
The grid is coarse. To pin the answer down, rerun with a finer grid
between the last n that failed and the first that passed,
and more trials per point.
Worked example 2: a binary outcome, adjusted versus unadjusted
SimulationFramework is convenient, but a plain loop is
short and shows every step. This example uses one.
The question. A binary outcome (an event occurs or not) with about a 40% control-arm risk. Treatment lowers the log odds by 0.75. One strong continuous prognostic covariate and one binary covariate are recorded at baseline. Under complete randomization, how many subjects are needed for 80% power, analyzing the risk difference with and without covariate adjustment?
draw_covariates2 = function(n) data.frame(x1 = rnorm(n), x2 = rbinom(n, 1, 0.4))
log_odds_control = function(X) -0.7 + 1.2 * X$x1 + 0.5 * X$x2
beta2 = -0.75 # treatment effect on the log-odds scaleThe effect is planted on the log-odds scale, but both analyses report a risk difference, so translate it. A large draw from the covariate distribution gives the marginal risks the trial would see:
set.seed(1)
X_big = draw_covariates2(1e6)
risk_c = mean(plogis(log_odds_control(X_big)))
risk_t = mean(plogis(log_odds_control(X_big) + beta2))
c(control = risk_c, treated = risk_t, risk_difference = risk_t - risk_c)
#> control treated risk_difference
#> 0.4045964 0.2740873 -0.1305091The planted effect is a drop from 40.5% to 27.4%, a risk difference
of -13.1 percentage points. The two analyses are
InferenceIncidGCompRiskDiff (a logistic model with the
covariates, standardized to a marginal risk difference) and
InferenceIncidNewcombeRiskDiff (the unadjusted
two-proportion comparison). Each simulated trial is analyzed both ways,
so the two power curves share the same trials.
one_trial2 = function(n, beta, seed) {
set.seed(seed) # one seed per trial
X = draw_covariates2(n)
des = DesignFixediBCRD$new(n = n, response_type = "incidence", verbose = FALSE)
des$add_all_subjects_to_experiment(X)
des$assign_w_to_all_subjects()
w = des$get_w()
des$add_all_subject_responses(rbinom(n, 1, plogis(log_odds_control(X) + beta * w)))
c(adjusted = InferenceIncidGCompRiskDiff$new(des, verbose = FALSE)$compute_asymp_two_sided_pval(),
unadjusted = InferenceIncidNewcombeRiskDiff$new(des, verbose = FALSE)$compute_asymp_two_sided_pval())
}
rejection_rates2 = function(n, beta, R, seed0) {
pvals = vapply(seq_len(R), function(i) one_trial2(n, beta, seed0 + i), numeric(2))
rowMeans(pvals < alpha)
}
ns2 = c(150L, 250L, 350L, 450L, 550L)
R2 = 500L
pow2 = t(sapply(ns2, rejection_rates2, beta = beta2, R = R2, seed0 = 0L))
rownames(pow2) = paste0("n=", ns2)
pow2
#> adjusted unadjusted
#> n=150 0.448 0.380
#> n=250 0.694 0.584
#> n=350 0.838 0.758
#> n=450 0.922 0.854
#> n=550 0.968 0.900
n_pick2 = apply(pow2, 2, function(p) smallest_n(ns2, p, R2))
n_pick2
#> adjusted unadjusted
#> 350 450
With 500 trials per point, the smallest grid n whose
lower bound clears 80% is n = 350 for the adjusted
analysis and n = 450 for the unadjusted one. At n = 350
the adjusted analysis has power 83.8% and the unadjusted one 75.8%. Here
the design is fixed and the analysis changes the sample size: adjusting
for a covariate that predicts the outcome buys power for free.
The loop uses the same seeds (seed0 + i) at every
n. Using common random numbers like this makes the curves
smoother than independent seeds would, since neighboring points share
much of their noise. It does not bias any single point.
Checking size too
A power curve answers “how often does the test reject when the effect
is real?” It is only useful if the test rejects about alpha
of the time when there is no effect. A test that rejects 9% of the time
under the null at your n will also look more powerful than
it is. Its “power” is partly false positives, and the sample size you
read off it is too small.
The procedure-trust article
explains which procedures are valid at every sample size (exact and
randomization tests) and which only as n grows (Wald,
likelihood-ratio, bootstrap and others). The Wald p-values used above
are in the second group, so check them by simulation at the
n you chose: same setup, betaT = 0.
For example 1, SimulationFramework reports
size and an exact binomial test of it against
alpha (size_pval) when
betaT = 0:
R_size = 500L
sim1_null = SimulationFramework$new(
response_type = "continuous",
design_classes_and_params = list(DesignFixediBCRD = list(), DesignFixedBinaryMatch = list()),
inference_classes_and_params = list(InferenceContinOLS = list(), InferenceContinKKOLSOneLik = list()),
n = unique(as.integer(c(n_pick1["crd"], n_pick1["m_kk"]))), p = 2L, betaT = 0, sd_noise = 1,
alpha = alpha, Nrep_W = R_size,
custom_replication_data_generator = generator,
inference_types_and_params = list(asymp_pval = list()),
results_filename = tempfile(fileext = ".csv"), continue_from_last_result_row = FALSE,
seed = 7001L, num_cores = 2L, verbose = FALSE
)
sim1_null$run()
size1 = as.data.frame(SimulationFrameworkReport$new(sim1_null)$summarize())
size1$analysis = paste(sub("^Design", "", size1$design), "+", sub("^Inference", "", size1$inference))
size1 = cbind(size1, mc_bounds(size1$size, size1$n_size))
size1 = size1[(size1$analysis == analyses1["crd"] & size1$n == n_pick1["crd"]) |
(size1$analysis != analyses1["crd"] & size1$n == n_pick1["m_kk"]), ]
size1[, c("n", "analysis", "size", "lower", "upper", "size_pval")]
#> n analysis size lower upper
#> 1 70 FixedBinaryMatch + ContinKKOLSOneLik 0.054 0.034189039 0.07381096
#> 2 70 FixedBinaryMatch + ContinOLS 0.014 0.003701699 0.02429830
#> 6 150 FixediBCRD + ContinOLS 0.046 0.027638160 0.06436184
#> size_pval
#> 1 0.6807127508
#> 2 0.0000323695
#> 6 0.7585450748
size_of = function(a) size1$size[size1$analysis == analyses1[a]]
row_of = function(a) size1[size1$analysis == analyses1[a], ]At the chosen sample sizes the rejection rates under no effect are 4.6% (complete randomization + OLS), 5.4% (matched analysis) and 1.4% (plain OLS on the matched design), each with a Monte Carlo standard error of about 1.0 percentage points.
Plain OLS on the matched design rejects well below 5%. This is the overstated standard error seen above: the analysis is conservative, which costs power but does not invalidate it.
The matched analysis rejects 5.4% at n = 70, close to 5%.
For example 2, check both the chosen n and a small
one:
R_size2 = 1000L
n_small = 60L
size2 = rbind(rejection_rates2(n_pick2["adjusted"], beta = 0, R = R_size2, seed0 = 1e6),
rejection_rates2(n_small, beta = 0, R = R_size2, seed0 = 2e6))
rownames(size2) = paste0("n=", c(n_pick2["adjusted"], n_small))
size2
#> adjusted unadjusted
#> n=350 0.050 0.043
#> n=60 0.057 0.049
small_lower = mc_bounds(size2[2, "adjusted"], R_size2)$lowerAt n = 350 the adjusted test rejects 5.0% of null trials, so its power there can be trusted. At n = 60 it rejects 5.7% (lower 95% bound 4.3%, from 1000 trials), not clearly above the nominal 5%. Even so, check size at your own n: the Wald test for a fitted logistic model is only asymptotically valid.
A sequential design
Many trials enroll subjects one at a time, and the design must assign
each on arrival. DesignSeqOneByOneKK21 matches each new
subject to an earlier unmatched one when their covariates are close, so
pairs form as the trial runs. In a simulation the per-subject loop sits
inside the per-trial loop. Here is power at the sample size example 1
chose for the fixed matched design, with the same outcome model and
effect, analyzed by the matched class
InferenceContinKKOLSOneLik (as in the continuous cookbook):
one_trial_seq = function(n, beta, seed) {
set.seed(seed)
X = draw_covariates(n)
mu = outcome_model(X)
des = DesignSeqOneByOneKK21$new(n = n, response_type = "continuous", verbose = FALSE)
for (i in seq_len(n)) { # subjects arrive one by one
w_i = des$add_one_subject_to_experiment_and_assign(X[i, , drop = FALSE])
des$add_one_subject_response(i, mu[i] + beta * w_i + rnorm(1))
}
InferenceContinKKOLSOneLik$new(des, verbose = FALSE)$compute_asymp_two_sided_pval()
}
n_seq = as.integer(n_pick1["m_kk"])
R_seq = 200L
p_seq = vapply(seq_len(R_seq), function(i) one_trial_seq(n_seq, beta1, 3e6 + i), numeric(1))
power_seq = mean(p_seq < alpha)
cbind(power = power_seq, mc_bounds(power_seq, R_seq))
#> power lower upper
#> 1 0.815 0.7611857 0.8688143At n = 70 the sequential matching design has power 81.5% (95%
interval 76.1% to 86.9%, from only 200 trials because each sequential
trial is slower to simulate), against 91.2% for the fixed matched design
that sees every subject before pairing. A sequential design cannot match
as well as one that waits for all the covariates, so expect some loss,
and check the size at your n as above before using the
number. SimulationFramework also accepts sequential design
classes (its reference example runs DesignSeqOneByOneKK21)
and runs this per-subject loop for you.
Practical tips
Seeds. Give each simulated trial its own seed,
derived from its index (seed0 + i above,
seed + i inside SimulationFramework), rather
than setting one seed at the top and running everything in sequence.
Then any single trial can be reproduced on its own, and the results do
not depend on how trials are split across cores. Reproducibility explains how EDI seeds
designs, resampling and SimulationFramework.
Cores. SimulationFramework parallelizes
over replications with num_cores (this article uses 2). In
your own loop, wrap the per-trial function in
parallel::mclapply() (Unix) or a
mirai/future map, keeping the per-trial seed.
When the trials run in parallel, leave each inference object at
num_cores = 1 so the two levels of parallelism do not
compete for the same cores.
Speed. Screen sample sizes with asymptotic p-values,
which take milliseconds. Randomization and bootstrap p-values repeat the
analysis hundreds of times per trial, so run them only at the final
n, to confirm the power and size of the procedure you will
report. For example:
sim_final = SimulationFramework$new(
response_type = "continuous",
design_classes_and_params = list(DesignFixedBinaryMatch = list()),
inference_classes_and_params = list(InferenceContinKKOLSOneLik = list()),
n = as.integer(n_pick1["m_kk"]), p = 2L, betaT = c(0, beta1), Nrep_W = 2000L,
custom_replication_data_generator = generator,
inference_types_and_params = list(asymp_pval = list(), rand_pval = list(r = 499L)),
results_filename = "final_check.csv.bz2", seed = 2026L, num_cores = 8L
)
sim_final$run()
SimulationFrameworkReport$new(sim_final)$summarize()With results_filename on disk and
continue_from_last_result_row = TRUE (the default), an
interrupted run resumes where it stopped.
Report what you assumed. A simulated sample size is
only as good as its inputs, so the protocol should state them: the
design and its settings; the analysis class, procedure and
alpha; the effect size and its scale (mean difference, log
odds, risk difference); the outcome model, including how strongly each
covariate predicts the outcome and the noise level or baseline risk; the
covariate distribution; the number of simulated trials per point and the
resulting Monte Carlo error; the seed; and the size check at the chosen
n. A sensitivity run with a weaker covariate effect or a
smaller treatment effect shows how much the answer depends on them.
Where to go next
- Get started: the design, assign, record, infer pattern.
-
Which procedure can I trust at my
sample size?: which tests hold their level at small
n. - Learn Statistics Through EDI: power, size and coverage by simulation, for teaching.
- The cookbooks, one per outcome type: continuous, incidence, count, proportion, survival, ordinal.
-
SimulationFrameworkandSimulationFrameworkReport: every option, including outcome types beyond these two.