The user wants a comprehensive lesson on experimental design covering these key topics:
- Randomization
- Blinding
- Blocking
- Factorial designs
- Power and sample size
- Confounding
- Analysis plans
- Preregistration
I'll structure this as a thorough educational resource with clear explanations and practical examples for each concept. # Comprehensive Guide to Experimental Design
Introduction: Why Design Matters
A well-designed experiment is the foundation of credible science. Poor design cannot be fixed by sophisticated analysis—the phrase "garbage in, garbage out" applies directly. This guide covers the core principles that protect against bias and maximize the information gained from your research.
1. Randomization
What It Is
Randomization is the random allocation of experimental units (subjects, plots, samples) to treatment conditions. It is the single most important feature distinguishing a true experiment from an observational study.
Why It Matters
- Eliminates systematic bias: Ensures no hidden variable determines who gets which treatment
- Balances unknown confounders: Variables you didn't measure or don't know about are probabilistically distributed equally across groups
- Justifies statistical inference: Creates the probabilistic basis for p-values and confidence intervals
Methods of Randomization
Simple Randomization
# Python example: simple randomization
import random
subjects = ['S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8']
random.shuffle(subjects)
treatment = subjects[:4]
control = subjects[4:]
print(f"Treatment group: {treatment}")
print(f"Control group: {control}")
Stratified Randomization
Randomize within strata to ensure balance on key variables.
# Stratified by sex
males = ['M1', 'M2', 'M3', 'M4']
females = ['F1', 'F2', 'F3', 'F4']
random.shuffle(males)
random.shuffle(females)
treatment = males[:2] + females[:2] # 2 males, 2 females
control = males[2:] + females[2:] # 2 males, 2 females
Block Randomization
Ensures equal group sizes after every k subjects (useful for sequential enrollment).
# Block size of 4: guarantees 2 treatment, 2 control per block
block = ['T', 'T', 'C', 'C']
random.shuffle(block)
# Result might be: ['C', 'T', 'C', 'T']
Example: Clinical Trial
Poor design: Assign the first 50 patients to receive the new drug, next 50 to placebo.
- Problem: Early patients may differ systematically from later patients (seasonality, changing referral patterns, physician learning)
Good design: Use computer-generated random numbers to assign each patient at enrollment.
- Each patient has equal, independent probability of each assignment
- Document the randomization seed for reproducibility
2. Blinding (Masking)
Levels of Blinding
| Level | Who is Blinded | Purpose |
|---|
| Single-blind | Participants only | Prevents placebo effects, demand characteristics |
| Double-blind | Participants AND researchers | Also prevents researcher bias in treatment delivery and outcome measurement |
| Triple-blind | Participants, researchers, AND analysts | Also prevents bias in data analysis |
Why Each Level Matters
Participant blinding prevents:
- Placebo effects (expecting benefit → experiencing benefit)
- Nocebo effects (expecting harm → experiencing harm)
- Differential dropout (control group leaves due to disappointment)
- Reporting bias (treatment group reports more positively)
Researcher blinding prevents:
- Differential treatment (unconsciously giving more attention to treatment group)
- Biased outcome assessment (seeing improvement you expect to see)
- Leading questions in interviews
Analyst blinding prevents:
- Selective analysis approaches favoring desired outcomes
- "Trying different things until it works"
Example: Drug Trial Design
Design for testing anti-anxiety medication:
1. Pharmacy prepares identical capsules:
- Active: contains medication
- Placebo: contains inert filler
2. Capsules coded (A, B) - code held by pharmacist only
3. Study nurse (blinded) administers capsules per randomization schedule
4. Outcome assessor (blinded) rates anxiety using structured interview
5. Statistician (blinded) analyzes "Group A vs Group B"
6. Code broken ONLY after analysis is locked
When Blinding Is Impossible
Some interventions cannot be blinded (surgery vs. medication, psychotherapy vs. medication). Solutions:
- Blinded outcome assessment: Assessor doesn't know treatment assignment
- Objective outcomes: Use blood tests, imaging, administrative records
- Active controls: Compare two active treatments rather than treatment vs. nothing
3. Blocking
What It Is
Blocking groups experimental units that are similar to each other, then randomizes treatments within each block. This controls for known sources of variability.
The Logic
Variability between blocks is removed from the error term → more precise treatment effect estimates → higher statistical power.
Common Blocking Factors
| Field | Common Blocking Factors |
|---|
| Agriculture | Field location, soil type, slope |
| Clinical trials | Study site, age group, disease severity |
| Psychology | Time of day, experimenter, testing room |
| Manufacturing | Machine, shift, raw material batch |
Example: Agricultural Field Trial
Testing 4 fertilizer types (A, B, C, D) across a field with known fertility gradient.
Without blocking (Completely Randomized Design):
Field layout (random assignment):
┌───┬───┬───┬───┐
│ A │ A │ B │ D │ (poor soil)
├───┼───┼───┼───┤
│ C │ B │ A │ C │ (medium soil)
├───┼───┼───┼───┤
│ D │ D │ C │ B │ (rich soil)
└───┴───┴───┴───┘
Problem: Fertilizer D happens to be on rich soil more often.
Any "D effect" might just be soil fertility.
With blocking (Randomized Complete Block Design):
Each row is a block (soil type). Each treatment appears once per block:
┌───┬───┬───┬───┐
│ B │ D │ A │ C │ Block 1 (poor soil)
├───┼───┼───┼───┤
│ A │ C │ D │ B │ Block 2 (medium soil)
├───┼───┼───┼───┤
│ C │ A │ B │ D │ Block 3 (rich soil)
└───┴───┴───┴───┘
Every fertilizer tested equally in each soil type.
Soil differences are statistically controlled.
Matched Pairs: A Special Case
When you have only two treatments, pair similar units and randomize within pairs.
Example: Testing a reading intervention
Pair students by pre-test reading score:
Pair 1: Student A (score 45) and Student B (score 46)
→ Flip coin: A gets intervention, B gets control
Pair 2: Student C (score 62) and Student D (score 61)
→ Flip coin: D gets intervention, C gets control
Analysis: Compare differences within pairs
Within-Subject Blocking (Repeated Measures)
Each subject serves as their own block, receiving all treatments.
Crossover Design for migraine medication:
Period 1 Washout Period 2
--------- ------- ---------
Subject 1: Drug A → Drug B
Subject 2: Drug B → Drug A
Subject 3: Drug A → Drug B
Subject 4: Drug B → Drug A
Advantage: Controls for all stable individual differences
Disadvantage: Carryover effects may persist
4. Factorial Designs
What They Are
Factorial designs study two or more factors simultaneously, with every combination of factor levels included.
Notation
A 2×3 factorial has:
- Factor A with 2 levels
- Factor B with 3 levels
- 2 × 3 = 6 treatment combinations
Why Use Factorials?
Efficiency: Test multiple factors in one experiment rather than separate experiments.
Interactions: Discover whether the effect of one factor depends on the level of another.
Example: 2×2 Factorial in Education
Research question: How do teaching method and class size affect test scores?
Factors:
- Teaching method: Traditional lecture vs. Active learning
- Class size: Small (20) vs. Large (60)
Design:
Small Class Large Class
----------- -----------
Traditional Condition 1 Condition 2
(n=25) (n=25)
Active Learning Condition 3 Condition 4
(n=25) (n=25)
Possible results and interpretations:
Scenario A: No interaction (additive effects)
Small Large
Traditional 60 55 ← Large classes -5 points
Active Learning 75 70 ← Large classes -5 points
↑ ↑
Active +15 in both cases
Main effect of Method: +15 points for active learning
Main effect of Size: -5 points for large classes
The effects simply add together: Active + Small = 60+15=75 ✓
Scenario B: Interaction present
Small Large
Traditional 60 55 ← Large classes -5 points
Active Learning 75 60 ← Large classes -15 points
Active learning helps more in small classes (+15)
than in large classes (+5).
Cannot describe effects without considering the other factor.
Visualizing Interactions
Test Scores
80 |
| ●------● Small + Active = Best
75 | /
| /
70 | ● ○------○ Large + Active
| \ /
65 | \ /
| \ /
60 | ●------● Small + Traditional
55 | ○ Large + Traditional
|________________________
Traditional Active
Parallel lines = No interaction
Non-parallel lines = Interaction present
2^k Factorial Designs
Common in industrial/engineering research. All factors have 2 levels (often coded as -1 and +1).
Example: 2³ design for chemical yield
Factor A: Temperature (Low=-1, High=+1)
Factor B: Pressure (Low=-1, High=+1)
Factor C: Catalyst (Type X=-1, Type Y=+1)
Run | A | B | C | Yield
----|----|----|----|-----
1 | -1 | -1 | -1 | 45
2 | +1 | -1 | -1 | 52
3 | -1 | +1 | -1 | 48
4 | +1 | +1 | -1 | 63
5 | -1 | -1 | +1 | 51
6 | +1 | -1 | +1 | 59
7 | -1 | +1 | +1 | 54
8 | +1 | +1 | +1 | 72
8 runs test 3 main effects + 3 two-way interactions + 1 three-way interaction
Fractional Factorials
When full factorial is too expensive, use a fraction.
2^(k-p) design: Uses 2^(k-p) runs instead of 2^k runs.
Trade-off: Some effects become aliased (confounded with each other).
5. Power and Sample Size
Key Concepts
Statistical Power: Probability of detecting an effect when it truly exists.
- Power = 1 - β (where β = Type II error rate)
- Convention: aim for power ≥ 0.80
The Power Equation involves four quantities (know any three, solve for the fourth):
┌────────────────────────────────────────────────────────────┐
│ 1. Effect Size (d, Cohen's d, R², η², etc.) │
│ 2. Sample Size (n) │
│ 3. Significance Level (α, typically 0.05) │
│ 4. Power (1 - β, typically 0.80) │
└────────────────────────────────────────────────────────────┘
Effect Size Conventions (Cohen's d)
| d | Interpretation | Example |
|---|
| 0.2 | Small | Subtle psychological effects |
| 0.5 | Medium | Noticeable practical difference |
| 0.8 | Large | Obvious, dramatic difference |
Sample Size Formulas
For two-group comparison (equal n per group):
n per group = 2 × [(z_α/2 + z_β)² × σ²] / δ²
Where:
z_α/2 = 1.96 for α = 0.05 (two-tailed)
z_β = 0.84 for power = 0.80
σ = standard deviation
δ = minimum detectable difference
Quick reference table (two groups, α=0.05, power=0.80):
| Effect Size (d) | n per group | Total N |
|---|
| 0.2 (small) | 393 | 786 |
| 0.5 (medium) | 64 | 128 |
| 0.8 (large) | 26 | 52 |
Power Analysis in R
# Two-sample t-test power analysis
library(pwr)
# Q: "What sample size to detect d=0.5 with 80% power?"
pwr.t.test(d = 0.5, sig.level = 0.05, power = 0.80, type = "two.sample")
# Result: n = 63.77 per group → use 64 per group
# Q: "What power do I have with n=30 per group, expecting d=0.6?"
pwr.t.test(n = 30, d = 0.6, sig.level = 0.05, type = "two.sample")
# Result: power = 0.61 (underpowered!)
# ANOVA: 4 groups, medium effect size (f=0.25)
pwr.anova.test(k = 4, f = 0.25, sig.level = 0.05, power = 0.80)
# Result: n = 45 per group
# Correlation
pwr.r.test(r = 0.3, sig.level = 0.05, power = 0.80)
# Result: n = 84 total
Power Analysis in Python
from statsmodels.stats.power import TTestIndPower
analysis = TTestIndPower()
# Find required n for d=0.5, alpha=0.05, power=0.80
n = analysis.solve_power(effect_size=0.5, alpha=0.05, power=0.80)
print(f"Required n per group: {n:.0f}") # Output: 64
# Find power for given n and effect size
power = analysis.solve_power(effect_size=0.5, nobs1=30, alpha=0.05)
print(f"Power: {power:.2f}") # Output: 0.48
Power Curves
Power
1.0 | ___________
| ____/
0.8 | ______/ ← Target power
| ___/
0.6 | __/
| _/
0.4 | _/
|/
0.2 |
|
0.0 |_________________________________
0 50 100 150 200 250 300 n
Sample size needed depends heavily on effect size:
── Large effect (d=0.8)
── Medium effect (d=0.5)
── Small effect (d=0.2)
Common Mistakes in Power Analysis
- Computing post-hoc power using the observed effect size (circular reasoning)
- Using unrealistic effect sizes based on pilot studies (overestimates)
- Forgetting attrition: If you expect 20% dropout, recruit n/0.8
- Ignoring clustering: Patients within doctors, students within classrooms require adjusted formulas
6. Confounding
What It Is
A confound is a variable that:
- Is associated with the treatment/exposure
- Is associated with the outcome
- Is NOT on the causal pathway from treatment to outcome
Confounding makes it impossible to determine whether the treatment or the confound caused the observed effect.
Visual Representation
Confound (C)
↙ ↘
Treatment (T) → Outcome (Y)
If C → T and C → Y, then the T-Y association may be spurious
Classic Examples
Example 1: Ice cream and drowning
Hot Weather
↙ ↘
Ice Cream ←?→ Drowning
Observation: Ice cream sales correlate with drowning deaths
Reality: Hot weather causes both (more swimming + more ice cream)
Ice cream doesn't cause drowning
Example 2: Hospital quality paradox
Disease Severity
↙ ↘
Hospital Choice → Death
Better hospitals may have higher mortality rates because they
receive sicker patients. Severity confounds the hospital-death relationship.
Controlling for Confounders
At design stage (preferred):
| Method | How it works |
|---|
| Randomization | Distributes all confounders equally across groups |
| Restriction | Limit study to one level of confounder (e.g., only males) |
| Matching | Pair treated/control units on confounder values |
| Blocking | Randomize within levels of the confounder |
At analysis stage:
| Method | How it works |
|---|
| Stratification | Analyze separately within confounder levels |
| Regression | Include confounder as covariate |
| Propensity scores | Match/weight by probability of treatment |
Example: Analyzing with Confounders
# Naive analysis (ignoring confounder)
model_naive <- lm(outcome ~ treatment, data = mydata)
# Adjusted analysis (including confounder)
model_adjusted <- lm(outcome ~ treatment + confounder, data = mydata)
# Compare results
summary(model_naive)$coefficients["treatment", ]
summary(model_adjusted)$coefficients["treatment", ]
# If treatment effect changes substantially, confounding was present
Causal Diagrams (DAGs)
Directed Acyclic Graphs help identify what to control for:
Example: Does exercise reduce depression?
Age → Exercise ← Motivation
↓ ↓ ↓
└──→ Depression ←────┘
Age and Motivation are confounders (backdoor paths)
→ Control for Age and Motivation
But NOT: Exercise → Sleep → Depression
Sleep is a mediator (on the causal path)
→ Don't control for Sleep if you want total effect
Unmeasured Confounding
The biggest threat to causal inference. Even with statistical adjustment, you cannot control for variables you didn't measure.
Sensitivity analysis: Ask "How strong would an unmeasured confounder need to be to explain away the observed effect?"
7. Analysis Plans
What Is a Pre-Specified Analysis Plan?
A detailed document written BEFORE data collection (or at minimum, before looking at the data) that specifies:
- Primary outcome(s)
- Primary analysis method
- Secondary analyses
- How covariates will be handled
- Subgroup analyses
- How missing data will be addressed
- Criteria for statistical significance
Why Pre-Specify?
Problem: Researcher degrees of freedom
Same dataset, many defensible choices:
- Include or exclude outliers?
- Transform the outcome?
- Which covariates to adjust for?
- Which subgroups to examine?
- One-tailed or two-tailed test?
- Parametric or non-parametric?
These choices can flip results from "significant" to "not significant"
Solution: Lock in choices BEFORE seeing the outcome data.
Template Analysis Plan
# Statistical Analysis Plan
## Study: Effect of Mindfulness App on Stress Reduction
### 1. Study Design
Randomized controlled trial, parallel groups, 1:1 allocation
### 2. Primary Outcome
Perceived Stress Scale (PSS-10) score at 8 weeks
### 3. Primary Analysis
Intention-to-treat analysis comparing mean PSS-10 scores between
groups using ANCOVA with baseline PSS-10 as covariate.
Model: PSS_week8 ~ Treatment + PSS_baseline
Significance threshold: α = 0.05, two-tailed
Effect size: Cohen's d with 95% CI
### 4. Secondary Outcomes
- Anxiety (GAD-7) at 8 weeks
- Sleep quality (PSQI) at 8 weeks
- App engagement (minutes/week)
### 5. Subgroup Analyses
Treatment effect stratified by:
- Baseline stress (high vs. low, median split)
- Age group (<40 vs. ≥40)
Interaction tests will be conducted; significance level α = 0.10
### 6. Missing Data
Primary: Complete case analysis
Sensitivity: Multiple imputation (m=20, PMM method)
### 7. Protocol Deviations
Per-protocol analysis as sensitivity (exclude those with <50% app usage)
### 8. Multiplicity
Secondary outcomes: Report unadjusted p-values; interpret with caution
Subgroups: Exploratory only, not confirmatory
---
Version: 1.0
Date: 2024-01-15
Locked prior to any outcome data collection
Statistical Analysis Plan vs. Analysis Script
| Document | When Written | Contents |
|---|
| SAP (prose) | Before data collection | Describes planned analyses in words |
| Analysis script | Before unblinding | Actual code that will be executed |
Gold standard: Write and timestamp both before seeing outcomes.
8. Preregistration
What Is Preregistration?
Formally documenting your hypotheses, design, and analysis plan in a public, time-stamped repository BEFORE data collection.
Why Preregister?
| Problem | How Preregistration Helps |
|---|
| HARKing (Hypothesizing After Results Known) | Hypotheses locked before data seen |
| Outcome switching | Primary outcome documented in advance |
| Selective reporting | All planned analyses on record |
| p-hacking | Analysis decisions made blindly |
| File drawer effect | Registered studies are discoverable |
Where to Preregister
| Platform | Best For | URL |
|---|
| OSF Registries | General research | osf.io |
| AsPredicted | Quick, simple format | aspredicted.org |
| ClinicalTrials.gov | Clinical trials (often required) | clinicaltrials.gov |
| PROSPERO | Systematic reviews | crd.york.ac.uk/prospero |
| AEA Registry | Economics | socialscienceregistry.org |
What to Include
Minimum requirements:
1. Research questions and hypotheses
2. Study design (experiment? survey? observational?)
3. Planned sample size and stopping rule
4. All measured variables
5. Which variable(s) are primary outcomes
6. Analysis plan for primary hypothesis
7. Any data exclusion criteria
Additional elements:
8. Secondary analyses
9. Exploratory analyses (acknowledged as exploratory)
10. Power analysis justification
11. Data collection timeline
12. Known limitations
Example: OSF Preregistration
# Preregistration: Sleep Duration and Cognitive Performance
## Study Information
Title: Effect of Sleep Extension on Working Memory in College Students
Authors: [Blinded for review]
Date: March 1, 2024
## Hypotheses
H1: Participants in the sleep extension condition (8+ hours/night)
will score higher on the N-back task than control participants.
H2: The effect of sleep extension on N-back performance will be
mediated by self-reported alertness.
## Design Plan
**Study type**: Experiment - randomized with two groups
**Blinding**: Single-blind (participants know condition; assessor doesn't)
**Study design**: Between-subjects
## Sampling Plan
**Existing data**: No existing data
**Data collection procedures**: Recruit from introductory psychology
**Sample size**: 128 participants (64 per group)
**Sample size rationale**: Power analysis (d=0.5, α=.05, power=.80)
**Stopping rule**: Fixed sample; will conclude after analyzing 128 completers
## Variables
**Manipulated variable**: Sleep instruction (8+ hrs vs. usual sleep)
**Measured variables**:
- N-back accuracy (primary DV)
- N-back reaction time (secondary)
- Karolinska Sleepiness Scale (mediator)
- Actigraphy-measured sleep duration (manipulation check)
**Indices**: N-back accuracy = (hits - false alarms) / total trials
## Analysis Plan
**Statistical models**:
- H1: Independent samples t-test; Cohen's d reported
- H2: Mediation analysis (Hayes PROCESS macro, Model 4, 10000 bootstraps)
**Inference criteria**: α = .05, two-tailed
**Data exclusion**: Exclude if:
- Failed attention checks (>2 errors)
- Actigraphy shows <6 hrs sleep in extension condition
- Prior participation in related study
**Missing data**: Complete case for primary; sensitivity with MI
**Exploratory analyses** (clearly labeled):
- Moderating effect of chronotype
- Dose-response relationship with actual sleep hours
Preregistration Timeline
┌─────────────────────────────────────────────────────────────────┐
│ 1. Develop hypothesis and design │
│ 2. Write preregistration ← Before this │
│ 3. Submit preregistration (gets timestamp) deadline │
│─────────────────────────────────────────────────────────────────│
│ 4. Collect data ← After this │
│ 5. Analyze per preregistered plan point │
│ 6. Report ALL preregistered analyses │
│ 7. Clearly label any non-preregistered analyses as exploratory │
└─────────────────────────────────────────────────────────────────┘
Deviations from Preregistration
Deviations happen—the key is transparency:
## Deviations from Preregistration
1. **Sample size**: Collected 118 instead of 128 due to semester end.
- Sensitivity: Minimum detectable effect is now d=0.53
2. **Exclusion criterion added**: Discovered 3 participants used
stimulant medications; excluded post-hoc. Results without
exclusion reported in supplement.
3. **Analysis change**: Used Welch's t-test instead of Student's
t-test due to unequal variances (Levene's p < .01).
Putting It All Together: Complete Example
Study: Testing a New Teaching Method
# Complete Experimental Design Document
## Research Question
Does interactive problem-based learning (PBL) improve statistics
exam performance compared to traditional lectures?
## Design: Randomized Controlled Trial with Blocking
### Randomization
- Unit: Students (n = 200)
- Method: Stratified block randomization
- Stratify by: Prior math courses (0-1 vs. 2+)
- Block size: 8 within each stratum
- Implementation: Randomization sequence generated in R using
set.seed(12345) before recruitment begins
### Blinding
- Students: Cannot be blinded (know their instructional method)
- Graders: Blinded (exams identified by number only)
- Analyst: Blinded (groups coded A/B until analysis complete)
### Blocking
- Factor: Instructor (4 instructors)
- Each instructor teaches one PBL and one traditional section
- This controls for instructor effects
### Factorial Element
- 2 × 2 design crossing:
- Teaching method (PBL vs. Traditional)
- Practice tests (Provided vs. Not provided)
- Allows testing of interaction
### Sample Size Justification
- Expected effect size: d = 0.5 (based on meta-analysis)
- α = 0.05, Power = 0.80
- Required n = 64 per cell × 4 cells = 256
- Expect 20% attrition → recruit 320
- Per instructor: 80 students (40 per method)
### Potential Confounders
| Confounder | How Addressed |
|------------|---------------|
| Prior math ability | Stratified randomization |
| Instructor quality | Blocking (each instructor does both) |
| Time of day | Classes randomly assigned to time slots |
| Student motivation | Measured; covariate in analysis |
### Analysis Plan
**Primary analysis**:
2 × 2 ANCOVA
- DV: Final exam score (0-100)
- IVs: Teaching method, Practice tests, Interaction
- Covariate: Prior GPA, Motivation score
**Model**:
Exam ~ Method + PracticeTest + Method:PracticeTest + PriorGPA + Motivation
**Secondary analyses**:
- Instructor random effect (mixed model)
- Per-protocol analysis (attendance ≥ 80%)
### Preregistration
- Platform: OSF
- Date: January 15, 2024
- Link: https://osf.io/xxxxx
- Includes: Hypotheses, design, materials, analysis code
Summary Checklist
Before running any experiment, verify:
Design
Power
Confounding
Analysis
Transparency
Further Reading
Books:
- Montgomery, D.C. Design and Analysis of Experiments
- Shadish, Cook, & Campbell. Experimental and Quasi-Experimental Designs for Generalized Causal Inference
- Rosenbaum, P. Observation and Experiment
Papers:
- Simmons et al. (2011). "False-Positive Psychology"
- Nosek et al. (2018). "The Preregistration Revolution"
Online Resources:
- OSF Preregistration templates: osf.io/registries
- CONSORT guidelines for trials: consort-statement.org
- G*Power software for power analysis: gpower.hhu.de