Skip to content
Tech Interview Prep
Technical interview guide

Gene Expression Analysis & RNA-Seq

Quantifying which genes are active and by how much: read counting, normalization, and differential expression testing.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v6
Editorial status
Reviewed

Scope: DESeq2, edgeR, voom, STAR, Salmon, kallisto, featureCounts, tximport and MultiQC source publications; GENCODE, GA4GH and ENCODE guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-6

Define pre-analysis RNA-seq QC.

Answer

What I'd say first (60–120s)

Assumptions: Illumina short reads, human or mouse, poly(A)-selected, 2x100, aligned with STAR to the matching Ensembl release, quantified with featureCounts. Every band below shifts for total-RNA, single-cell, or a non-model organism.

Pre-analysis QC is the measurements taken on raw reads and on the aligned BAM before quantification, plus the rules that turn them into keep / fail / review. It is triage, not a gate: the job is to separate "this sample is broken" from "this sample looks unusual for a reason I can name". A sample that fails QC and gets quantified anyway does not just waste a lane: it enters the design matrix as a global expression shift and drags the differential-expression result with it.

The checks, grouped by where they run

stagetooltypical band (human poly(A), 2x100)what a miss means
raw readsFastQC / fastpper-base median Q30+; FastQC warns below median Q25, fails below Q20quality collapse at the 3' end
adaptersFastQC adapter module<1%insert shorter than read length; read-through
duplicationFastQCrises with depth: 20–30% at 20M pairs, 50%+ at 100Mhigh duplication alone is not a defect
rRNARSeQC / Picard CollectRnaSeqMetrics<5–10%poly(A) selection or ribo-depletion failed
alignmentSTAR log>85% uniquewrong reference, contamination, degradation
distributionRSeQC read_distribution60–80% exonicintronic load = gDNA or degradation
strandednessRSeQC infer_experiment>0.90 in one fraction for dUTPflat ~0.25 across all four = wrong protocol
insert sizePicard CollectInsertSizeMetricsmedian above read lengthmedian below read length = adapter read-through
batchMultiQCsample-sample correlation, PCA, sex checkswap, batch effect

Worked trace: one failing sample in a 24-sample batch

S7: FastQC per-base median Q36, adapter 0.4%, duplication 61%. Duplication looks alarming, but the batch was sequenced to 90M pairs, so 61% is in line with the other 23 samples. STAR: 71% unique, 22% multi-mapped. RSeQC read_distribution: 45% intronic against a batch median of 12%. CollectRnaSeqMetrics: 12% rRNA against a batch median of 1.5%. infer_experiment: 0.24/0.25/0.25/0.26. No strandedness signal at all, where the rest of the batch sits at 0.94.

That combination is not a threshold problem. Flat strandedness plus 12% rRNA plus 45% intronic says the library prep failed, not that the sample is biologically odd. Arithmetic: 45% of 60M reads is 27M reads not measuring exons, leaving 33M effective. Under the 40M the DE design needs. Exclude and re-prepare; do not lower the cutoff.

Trade-offs

Fixed global thresholds are cheap and reproducible but break on total-RNA and non-model organisms. Per-batch adaptive thresholds (median ± 3 MAD) catch a single outlier but are blind to a batch-wide failure, because every sample moves together. The rule I use: hard-gate only metrics whose failure is unrecoverable downstream. Adapter read-through, wrong strandedness, <50% mapping. Everything confounded by depth or biology goes into a review band with a written reason.

Failure modes and how each is caught

  • One universal threshold: plot each metric against sequencing depth across the batch; a deep library failing a duplication cutoff is the tell.
  • Outlier dropped after seeing the DE result: procedural. Freeze the exclusion list with a timestamp before the DE run.
  • Sample swap: genotype concordance at common SNPs, or a sex check against metadata.
  • Batch-wide failure missed: compare batch medians to a historical baseline, not to each other.
  • Tool-version drift: pin versions in the workflow and diff the MultiQC version table; a STAR bump changes multi-mapping defaults and moves mapping rate with no sample change.
  • Partial report read as complete: MultiQC silently omits modules whose inputs are missing. Assert the expected module list is present before sign-off.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Validate RNA-seq library metadata.

Answer

Core answer (first 90 seconds)

"Validate" here means: confirm the metadata fields that change downstream numbers (strandedness, read orientation, RNA selection, fragment size, UMI) and prove each against the data, not the sample sheet. The sample sheet is a claim; the BAM is evidence.

The field that silently corrupts everything is strandedness. Get it backwards and featureCounts/HTSeq assign reads to the antisense feature: on a gene-dense annotation you keep maybe 20-30% of the signal, and on overlapping loci you assign reads to the wrong gene entirely.

Primary check: RSeQC infer_experiment.py on a 1-2M read subsample against a BED12 of the annotation. It reports the fraction of reads explained by each orientation pair. Decision rule:

  • 0.8 explained by 1++,1--,2+-,2-+ → forward/stranded (FR), featureCounts -s 1.

  • 0.8 explained by 1+-,1-+,2++,2-- → reverse/stranded (RF), -s 2. This is what dUTP protocols (Illumina TruSeq Stranded mRNA) produce.

  • both near 0.5 → unstranded, -s 0.

Then confirm with the counter: run featureCounts both ways and compare "Successfully assigned fragments". A correct strand gives ~70-90%; the wrong one drops to ~10-30% or shifts to antisense. If the two runs are within a few points, the library is unstranded and the metadata claiming stranded is wrong.

Mechanism: why the fraction separates cleanly: in a stranded library, read 1 is synthesized from one specific strand, so its alignment orientation relative to the transcript is fixed. infer_experiment counts mate pairs whose orientation matches each of the two possible conventions; a real stranded library puts ~95%+ in one bucket, unstranded splits ~50/50.

Trade-offs / borderline: 0.6-0.8 is the awkward zone: mixed libraries, or a protocol with partial strand retention. Don't guess. Run infer_experiment per read group (-r); if RGs disagree, the libraries were pooled from different preps: split them. If it's genuinely ambiguous, count unstranded (-s 0) and flag it; you lose the ability to resolve antisense overlaps but you don't silently misassign.

Auto-detection: Salmon -l A and kallisto infer libType from the data (ISF/ISR/IU). Convenient, but it's a second opinion, not a substitute: record the explicit libType in the metadata so the next pipeline doesn't re-guess.

Other fields, with the check that catches each:

fieldcheckthreshold / action
RNA selectionPicard CollectRnaSeqMetrics PCT_RIBOSOMAL_BASES>10-20% rRNA → poly-A selection failed; re-check
fragment distributionPicard CollectInsertSizeMetricsmedian ~150-250 bp for mRNA; bimodal → adapter contamination or degradation
degradationMEDIAN_5PRIME_TO_3PRIME_BIAS, RSeQC geneBody_coveragestrong 3' skew → degraded input, 3' bias in counts
UMIumi_tools / fgbio; duplicate rate8-12 bp UMI; missing UMI on a UMI protocol → duplicates uncorrected
copied metadataRG SM/LB/PU vs sample sheet, FASTQ headersmismatch → wrong sample attribution

Failure modes and detection:

  • Reversed convention: infer_experiment fraction flips; featureCounts assignment collapses. Cost: near-total loss of signal.
  • Mixed libraries: per-RG infer_experiment splits; symptom is a bimodal strandedness fraction. Split by RG.
  • Annotation overlap: unstranded counting assigns reads to both genes; detect by fraction of reads in overlapping exons.
  • Copied metadata: RG SM doesn't match the sample sheet; detect with Picard ValidateSamFile and a sample-sheet/FASTQ header diff.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Configure splice-aware alignment.

Answer

Core answer. Three things decide the configuration before any flag: read length and library strandedness, whether the FASTA and GTF are the same build, and whether I need novel-junction discovery or only annotated-junction quantification. For Illumina short reads with a decent annotation I use STAR 2.7.x.

Build the index once with the annotation baked in:

Shell
STAR --runMode genomeGenerate --runThreadN 16 \
  --genomeDir star_idx --genomeFastaFiles GRCh38.fa \
  --sjdbGTFfile gencode.v44.gtf --sjdbOverhang 99

--sjdbOverhang defaults to 100; set it to read length − 1, so 99 for 100 bp reads. It sets how much donor/acceptor sequence STAR stores per annotated junction, so leaving it at the default with 150 bp reads loses sensitivity on annotated junctions.

Shell
STAR --genomeDir star_idx --readFilesIn R1.fq.gz R2.fq.gz \
  --readFilesCommand zcat --runThreadN 16 \
  --outSAMtype BAM SortedByCoordinate \
  --outSJtype Standard --twopassMode Basic

Mechanism. STAR seeds reads against the genome, then chains seeds allowing a gap. A gap landing on GT..AG (CT..AC on the other strand) is scored as a canonical intron and emitted as an N in the CIGAR. Junctions pre-loaded from the GTF need only --alignSJDBoverhangMin bases of overhang (default 3); novel junctions need --alignSJoverhangMin (default 8). That asymmetry is the reason to pass the GTF at all: annotated junctions are cheap to call, novel ones are not. --alignIntronMax defaults to 0, which genomeGenerate resolves to at most 1,000,000 bp; if your organism has longer introns, raise it explicitly or reads spanning them get soft-clipped instead of spliced.

Two-pass (--twopassMode Basic) runs a first pass to discover novel junctions, then re-aligns with them added to the index. It helps on poorly annotated genomes and costs roughly 2× runtime.

Trade-offs. HISAT2 is lighter on memory and takes --known-splicesite-infile from hisat2_extract_splice_sites.py, with --max-intronlen defaulting to 500000. Pick it when RAM is the constraint or you are aligning many samples on one box. minimap2 -ax splice is the choice for long reads (ONT/PacBio): -G caps intron length (200k default in splice mode) and --junc-bed injects annotation. STAR wins on short-read sensitivity and speed but needs roughly 30 GB RAM for a human index.

Failure modes and how to detect them.

  • Build mismatch. STAR errors on mismatched chromosome names, but a same-named different-build pair produces garbage silently. Watch the mapped fraction from samtools idxstats and the novel-junction count: a spike means the annotation does not match the FASTA.
  • Strand error. Run RSeQC infer_experiment.py; if the library is stranded and you pass the wrong -s to featureCounts, about half the reads go unassigned.
  • Pseudogene multimapping. --outFilterMultimapNmax defaults to 10; reads from pseudogenes pile onto the parent gene. Check the MAPQ distribution and the NH tag.
  • Two-pass leakage. If you build one shared sjdb from a cohort and reuse it, sample A's novel junctions inform sample B's alignment and the samples stop being independent. Run two-pass per sample, or freeze one sjdb for all samples and document it.
  • Chimeric reads. STAR writes Chimeric.out.junction only when --chimSegmentMin is set (default 0, off; 12 is a common value). A real fusion has several split reads at the same breakpoint; a single read is usually a template-switch artefact.

Validation. Read SJ.out.tab: column 4 is strand, column 6 is 0 for novel and 1 for annotated, column 7 is the uniquely mapping read count. A healthy human sample is 90%+ annotated junctions. Then run RSeQC junction_annotation.py and bam_stat.py for the split-read fraction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Count fragments for gene-level differential analysis.

Answer

Core answer (say this first). You are building an integer gene × sample matrix for DESeq2/edgeR, so count fragments, one read pair is one count, not reads. State three assumptions up front: paired-end, stranded library prep, and a GTF on the same reference build as the BAM. Then pick a counter and a rule set, and read the unassigned summary before trusting the matrix.

For a stranded paired-end RNA-seq library the default I reach for is featureCounts:

featureCounts -T 8 -p --countReadPairs -s 2 \
  -t exon -g gene_id -a genes.gtf -o counts.txt sample.bam

-p declares paired-end; since Subread 2.0.0 it counts fragments by default and --countReadPairs makes that explicit (on Subread 1.x, -p counted each mate and roughly doubled every count). -s 2 is reverse-stranded, correct for Illumina TruSeq/dUTP mRNA libraries; -s 1 is forward-stranded, -s 0 unstranded. -t exon -g gene_id sums exon features into genes via the GTF's gene_id.

Why the rules change the matrix. A fragment is assigned by intersecting its aligned blocks with annotation intervals. Three decisions resolve the hard cases:

  • Overlap: a fragment hitting two genes (read-through, convergent antisense) is Unassigned_Ambiguity by default; -O counts it for both, --fraction splits it 1/k.
  • Multimapping: a fragment with several equally good alignments is Unassigned_MultiMapping unless -M; -M --fraction divides 1/n across loci.
  • Strand: with the wrong -s, a fragment in the antisense gene of a convergent pair is silently assigned to the wrong gene. The count is still an integer, so nothing looks broken.

Alternatives and when to use them. HTSeq-count (-m union -s reverse -t exon -i gene_id) is read-based and single-end oriented; for paired-end you must name-sort and it does not merge mates, so it is a poor fit here. Salmon (-l A) is alignment-free, quantifies transcripts, and its NumReads are estimated, non-integer; you get gene counts via tximport with countsFromAbundance="no". Use Salmon when you want transcript-level estimates and speed; use featureCounts when you need a defensible integer matrix tied to a GTF.

Failure modes and detection.

  • Reads counted twice: -p without fragment counting on old Subread → every count ~2×. Detect: total assigned ≈ 2× fragment count.
  • Exon vs gene mismatch: -g transcript_id or a GTF whose gene_id differs from the one DESeq2 expects → genes split or merged. Detect: gene count far above/below annotation.
  • Wrong strand: -s 0 on a stranded library. Detect: assignment rate drops and antisense genes gain counts.
  • Annotation build mismatch: GTF on hg19, BAM on GRCh38 → most reads Unassigned_NoFeatures. Detect: that category dominating the summary.
  • Silent unassigned majority: always print the summary; if Unassigned_NoFeatures + Unassigned_Ambiguity exceed ~20%, stop.

Worked check (illustrative figures). 30M fragments, TruSeq stranded. -s 2: 27.3M assigned (91%), 1.2M NoFeatures, 0.9M Ambiguity, 0.6M MultiMapping. Same BAM with -s 0: 23.4M assigned (78%). The 3.9M gap is fragments whose antisense partner gene now wins the overlap. Same BAM with -p on Subread 1.7: 54.6M "assigned". 2× inflation, fold changes unchanged but mean-variance and filtering wrong.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Choose expression units for two analysis goals.

Answer

The 90-second answer

Two goals, two units. For differential expression, testing whether a gene's expression differs between conditions, use raw integer counts, or transcript-level counts imported and aggregated with tximport, and let DESeq2 or edgeR estimate size factors. For descriptive within-sample abundance, "what share of this sample's transcripts is gene X", use TPM. Label the unit and the denominator on every number you report.

Why the split holds

DESeq2 and edgeR fit a negative binomial to integer counts. The mean-variance relationship they model (variance rising with the mean, with a per-gene dispersion) is a property of count data. DESeq2's median-of-ratios size factors correct for library composition across samples, which is exactly what a between-sample comparison needs.

TPM is a two-step within-sample normalization: divide each transcript's read count by its length in kb (RPK), sum the RPKs, then divide by that sum and multiply by 1e6. TPM sums to 1e6 in every sample by construction. That makes it right for "gene X is 12% of this sample's transcripts" and wrong for "gene X is up 2-fold in treated." Because the denominator is the sample's own total, if one gene's share rises, every other gene's TPM falls: a composition shift that masquerades as coordinated down-regulation.

Alternatives and when the default flips

  • FPKM/RPKM: same length normalization, reversed order (total reads first, then length), so FPKM does not sum to a constant. Prefer TPM over FPKM for descriptive work; neither belongs in a count model.
  • CPM: counts per million, no length normalization. Fine for the same feature across samples when length is constant (a fixed panel), not for genes of different length.
  • lengthScaledTPM (tximport's default abundance): scales transcript TPM to a common average transcript length across samples, so it is comparable across samples for descriptive plots. Still not a count-model input.
  • When the default flips: with spike-in controls, use the spike-in as the size factor instead of median-of-ratios, because composition-based normalization fails when most genes shift.

Failure modes and how you catch them

  1. Feeding TPM into DESeq2/edgeR. DESeq2 warns "some values in assay are not integers" and still runs, producing wrong dispersions. Detect: assert the assay is integer before building the object.
  2. Comparing TPM across samples for DE. Detect: run DE on counts and on TPM; the call sets disagree on genes in composition-shifted samples, or a spike-in moves without a real change.
  3. Double normalization: TPM then size factors, or re-normalizing an already-TPM matrix. Detect: column sums should be 1e6 after TPM; if they are not, something re-scaled.
  4. Summing isoform TPM to gene TPM without length weighting. Detect: compare against tximport's gene-level TPM; naive sums diverge for genes with length-heterogeneous isoforms.

Worked arithmetic

Gene X: 200 reads, 2 kb → RPK = 100. Sample A: total RPK = 1000 → TPM = 100/1000 × 1e6 = 100,000. Sample B: total RPK = 2000 (other genes doubled) → TPM = 100/2000 × 1e6 = 50,000. Same raw count, same length, TPM halved: pure composition. DESeq2 on counts calls this not differentially expressed; TPM alone suggests a 2-fold drop.

unitlength-normalizedsums to constantvalid count-model input
raw countsnonoyes
CPMno1e6no
FPKMyesnono
TPMyes1e6no
lengthScaledTPMyesnono

Salmon, kallisto and RSEM all emit both estimated counts and TPM; tximport carries counts, abundance and length into DESeq2 so you never hand-convert between units.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Quantify isoforms responsibly.

Answer

What "responsibly" means here

Before you touch a quantifier, fix three things: the reference you quantify against, the fragment model that matches your library, and the level you will report at. Which tool and which EM variant are downstream of those.

Concretely: pin a GENCODE release (v44, 2023) rather than "latest"; build the index with the whole genome as decoy so reads from unannotated or intronic sequence are not forced onto an annotated transcript; pass strandedness explicitly instead of trusting auto-detect. Salmon 1.10.2, kallisto 0.50.1 and RSEM 1.3.3 do the same job: pick one and record its version, because estimates are not portable across index builds.

Uncertainty is not optional

All three ship with uncertainty estimation off by default: Salmon's --numBootstraps and kallisto's -b default to 0, and RSEM needs --calc-ci. Turn it on, 100 replicates is the usual choice, or you have point estimates with no error bar, and isoform point estimates are exactly where the error bar decides the call.

Why the estimates are correlated

Reads hitting a shared exon are compatible with several isoforms, so the quantifier splits them by a model: EM in kallisto, VBEM with Gibbs sampling in Salmon. That split is a function of the current estimate for every competing transcript, so the estimates move together: pushing mass onto T1 pulls it off T2. The trace shows it.

Three transcripts, equal effective length, 100 reads in three equivalence classes: EC1 = {T1}, 30 reads; EC2 = {T1, T2}, 40; EC3 = {T2, T3}, 30.

iterθ1θ2θ3
00.3330.3330.333
10.5000.3500.150
20.5350.3750.090
30.5350.4070.058
40.5270.4350.038
∞0.5000.5000.000

From row 1 to row 2: EC2's 40 reads split 0.50:0.35, giving 23.5 to T1 and 16.5 to T2; EC3's 30 split 0.35:0.15, giving 21 to T2 and 9 to T3. Counts 53.5 / 37.5 / 9.0, renormalised to θ = (0.535, 0.375, 0.090). EM drives T3 to zero because once T2 has support, T2 explains EC3's reads at least as well. The point estimate says "T3 is absent"; the data, 30 reads in EC3, is entirely compatible with T3 being present. That gap is what the bootstrap interval is for, and it is why a differential-transcript-usage test on point estimates alone calls switches that are not there.

Transcript or gene

Aggregate to gene when the transcripts you care about share most of their sequence, when coverage is under roughly 10–20 reads per transcript, or when you have fewer than three biological replicates. The cost is real: gene-level sums hide isoform switching, which is often the biology. Defend isoform-level calls only when the transcripts differ by a cassette exon or retained intron long enough to give reads unique to each, coverage clears that threshold, and you tested with a method that consumes the inferential replicates (fishpond, DRIMSeq, sleuth) rather than a t-test on TPM.

Failure modes and how you see them

  • Reference mismatch: mapping rate below ~60–70%, or a spike in reads hitting decoys. Check the detected library type against your protocol.
  • Incomplete annotation: high decoy rate, or a large fraction of reads landing in no equivalence class.
  • Wrong fragment model: auto-detected strandedness disagreeing with the kit; re-run with the explicit flag and compare.
  • Overconfident switching: bootstrap CV above ~0.2 on the transcripts you are calling, or a flat p-value histogram across the DTU test.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Validate RNA-seq normalization.

Answer

First I'd pin down what "validate" means here. Normalization isn't a property of a dataset: it's a claim that the scaling factors removed technical variation without removing the biological effect you're testing. So validation is specific to the comparison, not to the file.

Two assumptions have to be stated up front. First, that most genes are not differentially expressed between the groups: that's what makes a median or a trimmed mean a usable reference. Second, that whatever anchor you use, spike-in or otherwise, was added proportionally to the material being sequenced. If either fails, no downstream statistic rescues it.

My core answer is three checks, cheapest first.

One: distribution diagnostics. Relative log expression (RLE) boxplots should sit centred on zero with comparable interquartile spread across samples, and an MA plot should be symmetric about M = 0 for the bulk of genes. If the RLE boxes shift by more than roughly half a log2 unit between groups, either the scaling is wrong or the composition assumption is broken.

Two: agreement between methods. Run DESeq2's median-of-ratios and edgeR's TMM on the same matrix. Median-of-ratios takes the geometric mean of each gene across samples as a pseudo-reference (dropping genes with a zero in any sample), forms a per-gene ratio, and takes the median across genes. TMM trims the 30% most extreme M values and 5% most extreme A values by default, then takes a weighted trimmed mean. Same assumption, different outlier weighting, so if their size factors disagree by more than roughly 10–20%, the data is telling you the assumption is shaky.

Three: an orthogonal anchor. ERCC (92 synthetic transcripts in four mixes) or SIRV spike-ins, or ddPCR on a handful of genes, give a scaling that doesn't depend on the composition assumption at all.

Here's the trace that shows why the median is robust. Four samples, four genes:

geneS1S2S3S4
g1100100100200
g25005005001000
g320202040
g4100100100400

g4 is genuinely 4x up in S4. Geometric means: g1 118.9, g2 594.6, g3 23.8, g4 141.4. Ratios in S4: 1.682, 1.682, 1.682, 2.828. Median = 1.682. Size factors come out 0.841 for S1–S3 and 1.682 for S4: a ratio of exactly 2, which is the true library scaling. The 4x gene didn't drag it. Flip it: if three of four genes were DE, the median would follow them and the size factor would be wrong. That's the failure boundary.

Failure modes, and how I'd catch each:

  • Global transcriptional shift: a drug that shuts down most transcription. Median-of-ratios absorbs it and every gene looks unchanged. Detection: spike-in ratio disagrees with the size factor by more than 2-fold. This is the case where you must use spike-ins.
  • One dominant transcript: globin in whole blood can be 50–70% of reads. Detection: top gene exceeds ~30% of counts. Fix: strip it, or switch to spike-ins.
  • Spike-in pipetting bias: the spike-in is only as good as the pipette. Detection: plot spike-in ratio against input RNA mass across a dilution series; it should be monotone and near-linear. If it isn't, you've normalized to your own pipetting error.
  • Batch interaction: size factors cluster by batch rather than by group. Detection: colour the size-factor plot by batch. Fix: put batch in the design; don't normalize it away.
  • Normalized counts treated as absolute: they're relative. Detection: ddPCR two or three genes and compare.

Trade-offs. Median-of-ratios is the default when you have many samples and a minority of DE genes. TMM is slightly more robust to a few extreme genes. Spike-ins are the only option under a global shift, but they cost money, add a pipetting failure mode, and are the wrong choice for single-cell or sub-nanogram inputs, where the spike-in ratio is dominated by input-mass variation rather than by composition. TPM and RPKM are for within-sample comparisons; never for DE.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Explain a gene-level count model.

Answer

The 90-second answer. A gene-level count model treats each gene's per-sample read count as a negative binomial draw whose mean is a size factor times a modeled expression level, with an extra-Poisson variance term that is gene-specific. You fit it through a log link, log mu_ij = log s_j + x_i' beta, so the design coefficients are log fold changes, and you test the coefficient you care about, then correct across genes. Assumptions that matter: 3–5 replicates per group, counts aggregated to gene level (not transcript), and the goal is per-gene differential expression rather than absolute quantification.

Why negative binomial, not Poisson. Poisson forces variance equal to the mean. Real RNA-seq counts don't obey that: biological variability between samples plus library-prep noise push variance above the mean, and a Poisson test on overdispersed data calls far too many genes significant. NB adds one parameter: Var(Y) = mu + mu²·alpha. At alpha = 0.1 and mu = 100, variance is 100 + 1000 = 1100, SD ≈ 33, against a Poisson SD of 10. Ignore alpha and you understate the noise threefold. alpha is the dispersion; edgeR calls its square root the BCV.

Where the mean comes from. s_j is a per-sample size factor, not the library size. DESeq2's default (estimateSizeFactors, type="ratio") takes, per gene, the ratio of its count to the geometric mean across samples, then the median of those ratios. edgeR's default is TMM, a trimmed mean of M-values that trims 30% of log-ratios and 5% of abundances. Both produce a scale that makes samples comparable without letting a few high-count genes dominate. x_i' beta is the design (condition, batch, whatever you put in) and the condition coefficient is the log fold change.

Dispersion is where the modelling actually happens. A per-gene MLE of alpha from three replicates is nearly useless: huge variance. So both packages shrink. DESeq2 fits a mean-dispersion trend (fitType="parametric" by default, "local" when the trend is irregular) and shrinks each gene's estimate toward it with an empirical Bayes prior; edgeR uses a weighted likelihood with prior.df = 10 in glmQLFit. That is a bias-variance trade: you accept a biased alpha for a gene whose true dispersion is extreme, in exchange for stable estimates everywhere else. At n ≥ 10 per group the shrinkage matters less; at n = 3 it decides whether the test is usable at all.

R
dds <- DESeqDataSetFromMatrix(counts, coldata, ~ batch + condition)
dds <- DESeq(dds)   # ratio size factors, parametric dispersion fit
res <- results(dds, contrast = c("condition","treated","ctrl"), alpha = 0.05)

Alternatives, and when not to use this. limma-voom transforms counts to log-CPM with precision weights and fits a linear model: faster, often better at large n or with complex designs, but it leans on a loess mean-variance fit that sparse counts can break. Poisson is defensible only for technical replicates where BCV ≈ 0.01. And one-dispersion NB is the wrong tool for single-cell or targeted panels with many zeros; there you want a zero-inflated model (zinbwave, MAST) or you accept that the mean-variance relation isn't NB.

Failure modes, and how you see them.

  • No replicates: dispersion isn't estimable. edgeR's guide says supply a fixed BCV: 0.4 for human samples, 0.01 for technical replicates: rather than pretend. Detection: the package warns, or your dispersion plot is a flat line.
  • Wrong offset: size factors computed on a filtered or zero-heavy gene set drift away from 1. Detection: plot size factors against library size; a size factor above ~2 on a normal library means something is off.
  • Dispersion trend failure: plotDispEsts shows the fitted curve missing the cloud. Switch fitType to "local", or look for a batch effect.
  • Influential outlier: one sample with an extreme count for one gene. DESeq2 computes Cook's distance and, with cooksCutoff=TRUE (the default), sets that gene's p-value to NA when it exceeds the 0.99 quantile of F(p, m−p). Detection: count the NAs in results().
  • Rank-deficient design: DESeq2 errors with "the model matrix is not full rank", usually condition nested in batch. Detection: qr(model.matrix(~condition+batch))$rank.
  • Treating the fit as causal: a significant coefficient means "given this model", not "this caused that". If condition is confounded with batch, no p-value fixes it. Detection: cross-tabulate condition against batch before you fit.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Diagnose abnormal dispersion estimates.

Answer

Core answer (first 90 seconds). Dispersion is the extra-Poisson variance of a gene's counts, and you never observe it: you observe three estimates per gene, and "abnormal" means they disagree in a specific way. In DESeq2 (checked against 1.38) run plotDispEsts(dds): black dots are gene-wise MLEs, the red line is the fitted mean–dispersion trend, blue circles are the final MAP estimates. The diagnostic question is which of the three is wrong, and the answer decides the fix. My order is: read the plot, check replicate count, check for an outlier sample, check the design matrix rank, check the count input, and only then touch moderation or drop samples.

Mechanism. A gene-wise MLE is computed from roughly n − p residual degrees of freedom, so with 3 vs 3 replicates it is estimated from ~4 df and scatters over orders of magnitude. The trend fit borrows strength across genes with similar means, and the MAP estimate is a posterior combination of the gene-wise value and the trend, weighted by their respective df. Few replicates → the prior dominates → a gene whose true dispersion is 10× the trend gets pulled down to the curve and produces a false positive; a gene genuinely below the trend gets pulled up and produces a false negative. That asymmetry is the whole reason dispersion diagnostics exist.

column in mcols(dds)what it issource of information
dispGeneEstper-gene MLE~n − p df, noisy
dispFittrend value at that gene's meanall genes
dispersionMAP, gene-wise shrunk to trendposterior of the two

Worked trace (illustrative numbers). A gene with 3 vs 3 replicates has dispGeneEst = 2.0, dispFit = 0.05. The MAP lands near 1.5: the gene-wise estimate still wins because its df is not tiny. The same gene in a 20 vs 20 design has ~36 df, so the MAP lands near 1.8. Same data, same trend, different shrinkage: this is why you cannot compare dispersion values across designs with different replicate counts.

Failure modes and how each is detected.

  • Too few replicates. Detection: dispGeneEst spread at a fixed mean spans two orders of magnitude. Cost: real dispersion differences are invisible, so you under-call variable genes.
  • Heterogeneous gene forced to trend. Detection: dispGeneEst far above dispFit for a handful of genes, and one sample with a large Cook's distance for those genes. Cost: false positives concentrated in exactly the genes you care about.
  • Outlier sample inflating many genes. Detection: PCA or sample clustering separates one sample; many genes carry high Cook's distance. DESeq2 replaces such counts with a trimmed mean when n >= minReplicatesForReplace, default 7.
  • Confounded design. Detection: qr(model.matrix(design))$rank < ncol(model.matrix(design)). Batch aliased with condition means dispersion absorbs batch and inflates.
  • Wrong count input. Detection: non-integer values. TPM or normalized counts make the negative-binomial dispersion meaningless.

Trade-offs and deciding criteria. Parametric fit (DESeq2 default) is smooth and stable with few genes; fitType="local" tracks the trend more closely but can overfit. edgeR's estimateDisp(..., robust=TRUE) downweights outlier genes when fitting the trend, which is the right lever when the trend itself is distorted. Excluding a sample changes the design and costs df; minReplicatesForReplace keeps the design. Decide by cause: technical failure (low library size, low mapping rate) → exclude; biological outlier with ≥7 replicates → let replacement handle it; systematic cloud above the trend → change the fit or use robust fitting, not gene exclusion.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How do you decide which genes to filter out before differential-expression testing, and how do you defend the threshold?

Answer

Filter on expression level, never on the test statistic. A gene's mean normalized count is approximately independent of its Wald or LRT statistic under the null, so dropping low-count genes before testing is valid; dropping genes because their p-value looked unimpressive is not, and it breaks FDR control.

I'd use the tool's own rule rather than a hand-rolled cutoff. edgeR's filterByExpr keeps a gene that reaches min.count = 10 counts in at least min.prop = 0.7 of the smallest group's samples, with min.total.count = 15 summed across the library. DESeq2 runs independent filtering by default (independentFiltering = TRUE, alpha = 0.1) and picks the mean-normalized-count threshold that maximises rejections at the target FDR.

r

edgeR 4.x, R 4.4

y <- DGEList(counts, group = coldata$condition) keep <- filterByExpr(y, group = coldata$condition) y <- y[keep, , keep.lib.sizes = FALSE] sum(!keep) # genes removed, log this

DESeq2 1.4x

dds <- DESeqDataSetFromMatrix(counts, coldata, ~ condition) res <- results(dds, alpha = 0.05, independentFiltering = TRUE) metadata(res)$filterThreshold

Why filtering gains power instead of losing it: BH sets the threshold for rank i at i·α/m. Worked example, hypothetical: 20,000 genes tested, 12,000 with mean normalized count below 5. Unfiltered, the top rank needs p ≤ 0.05/20,000 = 2.5e-6; filtered to 8,000 genes, p ≤ 0.05/8,000 = 6.25e-6, 2.5× looser. A gene at p = 5e-6 is called after filtering and missed before. The 12,000 dropped genes had almost no chance of reaching 2.5e-6, their counts are too low for the dispersion model to resolve a fold change, so the correction was paying for tests with no power.

rulefilter statistickeeps a gene induced in one condition only?
filterByExpr (edgeR/voom)CPM cutoff scaled to library size, min.count in ≥70% of smallest groupyes
DESeq2 independent filteringmean of normalized counts, threshold maximising rejectionsyes
rowSums(counts) >= nraw countsyes, but ignores library size
p-value or rank cutoffthe test statisticinvalid: FDR no longer controlled

Failure modes. Filtering on the test statistic or on a p-value threshold is the one that silently invalidates the whole result: the nominal FDR no longer holds, and you detect it by re-running with independent filtering and watching the rejection count change. A condition-dependent filter, "expressed in control samples", drops genes induced only in treatment; filterByExpr's min.prop exists to avoid exactly that, and you check known induced markers survive. A threshold tuned after seeing the DE list is p-hacking; the rule belongs in the script before results are read. Too aggressive a cutoff (min.count = 50) removes real signal from lowly expressed transcription factors sitting at 20-40 counts; sweep the threshold and plot DE-gene count against it, looking for the plateau where the count stops moving. Filtering raw counts when library sizes differ 10× biases toward the deepest libraries; use CPM or normalized counts.

Documentation: the rule, its parameters, genes before and after, and a sensitivity table across two or three thresholds, all in the versioned analysis script. That is what makes the choice defensible in review, not the number itself, but the evidence that the result is stable around it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Set differential-expression decision rules.

Answer

What I'd say first. A decision rule is four choices fixed before I look at any p-value: the tested family, the error criterion and procedure, the minimum effect size, and what gets reported. Everything else follows from those.

  1. Tested family. The set the error rate is computed over: usually genes passing an expression filter (say ≥10 counts in ≥3 samples), decided from the count matrix, not from the test result. If 12,000 genes are expressed, m = 12,000: not the 20,000 annotated, and not the 300 that looked interesting.

  2. Error criterion. FDR at α = 0.05 via Benjamini–Hochberg, unless there's a reason to deviate.

  3. Minimum effect. |log2FC| ≥ 1 (2-fold) alongside the adjusted p-value. With n = 6 per group a 1.05-fold change can reach adjusted p < 0.05; the effect floor is what keeps the hit list from being statistically real and biologically noise.

  4. Reporting. Every tested gene with its estimate, standard error and adjusted value, not only the rejections.

Why BH controls FDR. Sort the m p-values ascending; BH finds the largest k with p₍ₖ₎ ≤ (k/m)·α and rejects the first k. Worked example, m = 10,000, α = 0.05: the threshold at k = 200 is 200/10,000 × 0.05 = 0.001. If p₍₂₀₀₎ = 0.0009 and p₍₂₀₁₎ = 0.0012, BH rejects exactly 200 genes. The guarantee is E[FDP] ≤ α under independence or positive regression dependence (PRDS). Under arbitrary dependence it does not hold: Benjamini–Yekutieli divides α by Σ1/i and controls, at a large power cost.

Alternatives and when the choice changes.

procedurewhat it assumeswhen I'd pick it
BHindependence or PRDSdefault
Storey q-valueestimates π₀, the true-null fractionmany true effects; more power, but an underestimated π₀ loses control
IHWcovariate independent of p under the nullsignal concentrated in high-expression genes
BYarbitrary dependencesmall, correlated gene sets

The effect filter is not free. BH's guarantee covers the p-value rejection set. Intersecting it with |log2FC| ≥ 1 yields a smaller set with no 5% guarantee: in the trace above, if 140 of the 200 clear the effect floor, that 140 is not an FDR-0.05 set. If a guaranteed set is needed, test the effect directly (a moderated t on a contrast, or a thresholded null) rather than post-filtering.

Independent filtering. Filtering on a statistic independent of the p-value under the null (mean expression, say) is safe and buys power. Filtering on the observed fold change is not: it selects on the test statistic, and FDR inflates.

Failure modes and how I'd catch them. Raw p-value filtering: the reported table has no adjusted column. Family changed post hoc: the reported m doesn't match the pre-registered filter. No effect floor: the smallest |log2FC| among hits is 0.1. Dependence ignored: BH applied to a small co-regulated module without checking PRDS.

Winner's curse and replication. A gene is called partly because noise pushed it over the line, so its reported effect is inflated; shrinkage (DESeq2's lfcShrink with apeglm) pulls estimates toward the prior. Discovery data cannot replicate itself: replication needs independent samples.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Prioritize genes by effect size.

Answer

Ranking by effect size alone is a trap: the largest raw fold changes in a bulk RNA-seq contrast are usually low-count genes with huge variance. For a 3-vs-3 treatment/control experiment, I would rank by a shrunken log2 fold change from DESeq2::lfcShrink(type="apeglm"), then require a pre-specified biological threshold and an s-value cutoff. Assumptions: no batch confounding, size factors from median-of-ratios, independent filtering left on, and the contrast is the one I care about. A concrete default: |shrunken log2FC| >= 1 and svalue <= 0.05, with the threshold written down before looking at the ranking.

Why shrinkage changes the ranking: the raw MLE log2FC for a gene with normalized counts 1 and 10 is log2(10) ≈ 3.32. If its lfcSE is 2.5, the 95% interval is roughly 3.32 ± 4.9, i.e. -1.6 to 8.2. That gene is noise, but raw ranking puts it at the top. apeglm uses a heavy-tailed empirical-Bayes prior centered at zero; the posterior mean pulls low-information genes toward zero and leaves well-estimated large effects mostly alone. It returns shrunken LFCs, standard errors, and s-values in the DESeq2 results. s-values are analogous to adjusted p-values but are computed from the posterior, so they pair with the shrunken estimate.

R
library(DESeq2)
dds <- DESeqDataSetFromMatrix(countData, colData, ~ condition)
dds <- DESeq(dds)
res <- lfcShrink(dds, coef = "condition_treated_vs_control", type = "apeglm")
res <- res[order(-abs(res$log2FoldChange)), ]
res$svalue <= 0.05 & abs(res$log2FoldChange) >= 1

Credible alternatives and when not to shrink:

strategywhat it ranksuse whenfailure
raw log2FClargest rationever for prioritizationselects low-count noise
shrunken LFC (apeglm)stable effect sizeranking for follow-upcan hide a large, uncertain effect
ashrshrunken LFC with normal-mixture prioryou want a different priorsimilar, less heavy-tailed
Wald statistic / p-valueevidence against nullsignificance, not effect sizeranks tiny but precise effects
unshrunken LFC + CIunbiased estimatequantitative dose-responsehigh variance dominates ranking

Do not shrink when you need an unbiased effect estimate for a downstream model, or when you have many replicates and high counts where shrinkage is negligible. Shrinkage is a bias-variance tradeoff, not a license to ignore uncertainty.

Failure modes and how to catch them:

  • Ranking raw low-count ratios. Detect by checking baseMean and lfcSE; a gene with baseMean < 10 and lfcSE > 1 is suspect. Cost: follow-up experiments wasted on noise.
  • Mixing a shrunken estimate with the wrong test. Detect by confirming the s-value came from the same lfcShrink call, not from an unshrunken Wald test. Cost: inflated false positives.
  • Hiding a large uncertain effect. A gene with raw LFC 4 and lfcSE 3 may shrink to 1. Detect by inspecting the unshrunken LFC and its interval alongside the shrunken value. Cost: missed biology.
  • Choosing the threshold after seeing the ranking. Detect by pre-registering the cutoff or using a held-out set. Cost: inflated false discovery.
  • Reading a shrunken zero as no biology. A low-count gene shrunk to 0 means no evidence, not no effect. Detect by checking its s-value and normalized counts. Cost: false negatives.

Finally, inspect normalized counts and replicate consistency for the top genes. A gene that is high in one replicate and zero in the others is not a reliable effect-size leader, whatever the shrunken LFC says.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Construct a model with condition, batch, and sex.

Answer

Assumptions first. "Construct a model with condition, batch, and sex" means: build a design matrix for a linear model where condition is the effect you want to estimate and test, and batch and sex are covariates you include to remove their variance. I'll assume a two-level condition (control/treated), a categorical batch, a two-level sex, and a per-sample response: a normalized expression value, or a per-gene count under a limma/voom-style linear model. More condition levels just add columns; nothing below changes.

Core answer. Use treatment (dummy) contrasts, with the control condition, the first batch, and one sex as reference levels:

R
# R 4.3.x, limma 3.58
meta$condition <- relevel(factor(meta$condition), ref = "control")
meta$batch     <- factor(meta$batch)
meta$sex       <- factor(meta$sex)
mm <- model.matrix(~ condition + batch + sex, data = meta)
qr(mm)$rank          # must equal ncol(mm)
car::vif(mm)         # collinearity check

The intercept is the mean of the reference cell (control, batch 1, female). conditiontreated is the treated-minus-control difference holding batch and sex fixed: that is the coefficient you test. batchb2 and batchb3 absorb batch shifts; sexM absorbs the sex shift.

Worked trace. 12 samples, one per condition×batch×sex cell, reference levels control/b1/F:

sampleconditionbatchsexIntcond_trtbatch_b2batch_b3sex_M
1controlb1F10000
2controlb1M10001
3controlb2F10100
7treatedb1F11000
12treatedb3M11111

Five columns, rank 5, full rank. For this balanced design the columns are orthogonal, so VIF is 1 for every term; a rule of thumb is to worry above 5–10. kappa(mm) is a rougher, scale-dependent check: near 1.4 here.

Alternatives and trade-offs. Additive ~ condition + batch + sex assumes the treatment effect is the same in both sexes and every batch. If the effect plausibly differs by sex, use ~ condition * sex + batch: one extra parameter buys an interaction test, at the cost of power on the main effect. If batch has many levels, fixed effects eat (b−1) residual degrees of freedom; a random batch effect (lme4::lmer(y ~ condition + sex + (1|batch))) or limma::duplicateCorrelation spends fewer. If samples are paired (same subject before and after), model the subject directly, ~ subject + condition, which removes between-subject variance that batch and sex only partly capture.

Failure modes and detection.

  • Confounding: if every treated sample sits in one batch, cond_trt and batch_b3 are the same column. qr(mm)$rank < ncol(mm); limma reports "Coefficients not estimable". Fix by dropping the confounded term or redesigning.
  • Reference-level mistake: relevel not applied, so the sign of the condition coefficient flips. Check levels(meta$condition).
  • Numeric categorical: sex stored as 0/1 integers is fit as one continuous slope, not a factor. Check is.factor(meta$sex).
  • Missing level: a level present in metadata but absent after filtering leaves an all-zero column. Run droplevels() before model.matrix.
  • Row/column misalignment: design-matrix rows must match count-matrix columns. all(colnames(counts) == rownames(meta)): a silent mismatch assigns the wrong covariates to every sample.
  • Overfitting: parameters ≥ samples leaves no residual df. Check nrow(mm) - qr(mm)$rank.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

Define treatment effects with a genotype interaction.

Answer

Clarify first. Two genotypes, two treatments, a continuous outcome, treatment randomized within genotype. Fit the saturated 2×2 model:

y_i = β0 + β1·T_i + β2·G_i + β3·(T_i × G_i) + ε_i,   ε ~ N(0, σ²)

T ∈ {0,1} is control/drug, G ∈ {0,1} is genotype A/B, and the reference cell is (T=0, G=0).

Core answer. A treatment effect with a genotype interaction is a treatment effect that is not constant across genotypes. The estimand is the difference in the average treatment effect between the two genotype strata: a difference of differences:

τ_A = E[y | T=1, G=A] − E[y | T=0, G=A]
τ_B = E[y | T=1, G=B] − E[y | T=0, G=B]
interaction = τ_B − τ_A = β3

In this parameterization β1 = τ_A (the simple effect in the reference genotype), β2 is the genotype difference in the control arm, and β3 is the interaction. The treatment effect in genotype B is β1 + β3. So β1 alone is not "the treatment effect": it is the effect in one stratum.

Worked trace. Synthetic cell means, n = 20 per cell:

cellmean
A, control10.0
A, drug13.0
B, control10.0
B, drug11.0

β0 = 10.0, β1 = 13.0 − 10.0 = 3.0, β2 = 10.0 − 10.0 = 0.0, β3 = (11.0 − 10.0) − (13.0 − 10.0) = 1.0 − 3.0 = −2.0.

Reconstruct to check: mean(A, drug) = 10 + 3 + 0 + 0 = 13.0 ✓; mean(B, drug) = 10 + 3 + 0 − 2 = 11.0 ✓.

Direction: β3 = −2.0 means the drug effect is 2 units smaller in B than in A. τ_A = 3.0, τ_B = 1.0.

Reference levels: β1 and β2 are defined relative to (T=0, G=A). Recode G so B is the reference and β3 flips to +2.0 while every fitted mean is unchanged. The interaction's magnitude is invariant; its sign is not.

Scale: on the raw scale β3 is an additive difference of differences. On the log scale it is a ratio of fold-changes: a drug that halves the outcome in A and quarters it in B gives β3 = log(0.25) − log(0.5) = log(0.5) ≈ −0.69, i.e. the fold-change in B is half that in A. Fix the scale before fitting.

Trade-offs. Report the interaction contrast when the question is "does the effect differ by genotype"; report marginal means averaged over genotypes when the question is "does the drug work on average": the average can sit near zero while both strata carry real, opposite effects. With many genotypes, treat genotype as a random effect and estimate the variance of τ across genotypes instead of one β3 per genotype. Power: the interaction contrast has SE 2σ/√n versus σ√(2/n) for a simple effect. √2 times larger, so equal power for the same effect size needs twice the n per cell.

Failure modes and how to catch them.

  • Reversed sign: β3's sign depends on which level is the reference. Detect by printing the design matrix and coefficient names, not by eyeballing the estimate.
  • Wrong reference level: alphabetical factor coding silently makes mut the reference. Detect with levels().
  • Average mistaken for subgroup: reporting β1 as "the treatment effect". Detect by computing marginal means (emmeans) and comparing them to β1.
  • Non-estimable contrast: an empty cell makes the design matrix rank-deficient, so software drops a term or returns NA. Detect by comparing qr(model.matrix(fit))$rank to ncol.
  • Post hoc selection: testing every pairwise contrast and reporting the significant one. Detect by pre-specifying the contrast and reporting multiplicity-adjusted p-values.
  • Plot/model mismatch: crossing lines in the cell-mean plot but no interaction term in the fit. Detect by overlaying fitted lines on the cell means.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Model pre/post samples from the same donors.

Answer

Clarify first. Two things decide the model: how many timepoints each donor has, and whether every donor has all of them. "Pre/post" usually means two, but a baseline-plus-follow-ups design changes the answer. I'll assume two timepoints, one measurement each, and some donors missing one of them.

The core answer. Pre and post from the same donor are not independent: a donor who reads high at baseline reads high at follow-up. Model the donor as a random intercept:

y_ij = β0 + β1·time_ij + u_i + ε_ij, u_i ~ N(0, σ_u²), ε_ij ~ N(0, σ_ε²)

β1 is the mean within-donor change. The random intercept u_i absorbs each donor's stable level, so ε carries only within-donor noise. That is the whole mechanism: the between-donor variance leaves the error term, and the SE of β1 shrinks with it. The model implies a constant within-donor correlation ρ = σ_u²/(σ_u² + σ_ε²) between pre and post.

R: lmer(y ~ time + (1 | donor), data = df) (lme4 1.1-35, R 4.4). Python: smf.mixedlm("y ~ time", df, groups=df["donor"]).fit().

Worked trace. Six donors:

donorprepostd
1100108+8
2120126+6
39599+4
4140152+12
5110113+3
6105111+6

d̄ = 39/6 = 6.5. Σ(d_i − d̄)² = 51.5, s_d² = 51.5/5 = 10.3, s_d = 3.21, SE = 3.21/√6 = 1.31. t = 6.5/1.31 = 4.96, df = 5, p ≈ 0.004.

Treat the same rows as independent: pooled SD ≈ 17.6, SE of the difference = 17.6·√(2/6) = 10.2, t = 0.64, df = 10, p ≈ 0.54. Same data, same 6.5-point effect, and the pairing is the difference between a result and a null. The mixed model's time coefficient is exactly 6.5 here, the mean within-donor difference, and in the balanced case its SE matches the paired t-test's.

Alternatives and when to pick them.

approachuse whencost
paired t-testexactly 2 timepoints, complete pairsdrops any donor missing one timepoint
random-intercept mixed model>2 timepoints, unbalanced, missing, covariatesassumes MAR; needs enough donors to estimate σ_u²
GEE, exchangeable working correlationwant a population-average effect with robust SEmarginal, not subject-specific; needs many clusters
fixed-effects differencingwant to strip all time-invariant donor confounderscannot estimate donor-level covariate effects
RM-ANOVAbalanced, complete, few timepointssphericity assumption; listwise deletion

Failure modes, and how you catch them.

  • Missing pairs: the paired t-test silently drops the donor. Count complete pairs against total donors; if they differ, the n in your output is not your enrollment.
  • Duplicate donor ID: two donors collapse into one random effect, shrinking σ_u² and inflating the within-donor n. Assert (donor, time) is unique.
  • Ignored correlation: the trace above. P 0.004 becomes 0.54.
  • Carryover (crossover only): the first period's effect bleeds into the second. Test period × treatment; add a washout.
  • Time trend: a secular drift unrelated to treatment. Add a control arm or a time-varying covariate.
  • Sign error: coding post as 0 and pre as 1 flips β1. Check the coefficient's sign against the raw means.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Design replication for a two-condition RNA-seq study.

Answer

The 90-second answer

Two conditions means two decisions: how many independent biological units per arm, and how deep to sequence each. My default is 6 biological replicates per condition at 20–30M paired-end reads, and I'd buy a seventh replicate before a deeper lane. Assumptions: gene-level DE with DESeq2 or edgeR against a reference genome, a minimum effect of interest around 2-fold, and human or mouse primary tissue where between-donor variance dominates. Isogenic cell lines or isoform-level endpoints move both numbers.

Why replication, not depth

Replication buys the denominator. edgeR splits variance into a technical Poisson part and a biological part: the biological coefficient of variation. Human primary tissue runs around BCV 0.4; an isogenic cell line closer to 0.1. That number sets the sample size. For a single gene with known variance, n = 2(z_0.975 + z_0.8)²σ²/Δ² = 2(2.80)²(0.16)/1 ≈ 3 per arm at a 2-fold effect and BCV 0.4. That is a floor for one gene. Across ~20,000 genes with FDR control and dispersion estimated from the data, it is not the answer: Schurch et al. (RNA, 2016) benchmarked this and recommended at least 6 replicates per condition for reliable DE calls, 12 to recover nearly all DE genes. Tools that do this arithmetic for you: RNASeqPower, PROPER, powsimR.

Depth saturates. Gene-level counts stop improving past roughly 10–30M reads per sample; ENCODE's standard for human/mouse gene expression is 30M paired-end reads. A marginal replicate is a new draw from the biological distribution. A marginal 10M reads is precision on a draw you already have.

replicates/armwhat it buyswhat it misses
2ENCODE's minimum for a reference expression datasetdispersion from two points; FDR control unreliable
3the per-gene floor for a 2-fold effect at BCV 0.4small effects; unstable dispersion
6Schurch et al.'s recommendation; usable FDReffects below ~1.5-fold
12recovers nearly all DE genes in their benchmarkbudget

Check confounding before you sequence

R
# R 4.4, base stats
coldata <- data.frame(
  condition = factor(c("ctrl","ctrl","ctrl","trt","trt","trt")),
  batch     = factor(c("A","A","A","B","B","B"))
)
X <- model.matrix(~ batch + condition, coldata)
qr(X)$rank   # 2
ncol(X)      # 3

The batchB column is (0,0,0,1,1,1) and the conditiontrt column is (0,0,0,1,1,1): identical, so rank 2 against 3 columns. DESeq2's design = ~ batch + condition drops the condition coefficient and the contrast is not estimable. Run this check on the sample sheet, not after sequencing.

Failure modes and how you catch them

  • Pseudoreplication: three aliquots of one donor entered as n=3. Detection: the number of rows in the design must equal the number of independent donors; if donor IDs repeat, use limma's duplicateCorrelation or a mixed model (dream).
  • Donor reuse across arms: the same donor in both conditions is a paired design, not two independent groups. Detection: donor IDs appear under both condition levels. Switch to ~ donor + condition.
  • Cage or litter effects: cage-mates share microbiota, and the cage effect can exceed the treatment effect. Detection: fit cage as a random effect, or check the intraclass correlation across cages within a condition.
  • Unequal attrition: detection is comparing the planned sample sheet against the sequenced one; if dropout correlates with condition, the comparison is biased.
  • Batch confounding: the rank check above.

When depth wins instead

Isoform-level or splicing endpoints need 50–100M reads because junction reads are sparse. Allele-specific expression needs coverage over heterozygous sites. Low-input and single-cell work can be depth-limited per cell. In those cases I'd take 4 replicates at higher depth over 6 shallow ones.

What would change my answer: a pilot showing BCV near 0.1 (isogenic line) drops the count; a paired design halves the effective variance, so 4 pairs beat 6 unpaired.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Lay out samples across extraction batches and lanes.

Answer

What I'd say first

Assumptions I'd state out loud: the nuisance sources I know about are extraction batch and lane/position; the batch and lane counts are fixed; the samples are already collected and I can't add more. Direct answer: block on batch, keep every condition represented in every batch and every lane, randomize the leftover freedom (which sample lands in which well), and freeze the allocation plus any deviation in the run metadata before the first pipette tip.

Worked allocation

24 samples, 12 control (C) and 12 treated (T), two extraction batches, two lanes each, 6 samples per lane.

batchlaneCT
B1L133
B1L233
B2L133
B2L233

Within each batch the contrast Δ_b = mean(T) − mean(C) is free of the batch main effect, because both conditions see the same batch. Overall effect = (Δ_1 + Δ_2)/2.

Confounded version: B1 all C, B2 all T. The observed difference is then true effect + (batch2 − batch1). If the true effect is +2 and the batch offset is +5, the confounded design reports 7, and no arithmetic recovers 2. The balanced design reports 2 in each batch.

Cost of the balance: two batches give one degree of freedom for the batch effect, so you can remove it but you can't estimate its variance well. If you need that, use three or more batches, or add a bridge.

Alternatives and when to pick them

  • Randomized blocks (above): default when you know the nuisance source and every batch can hold every condition.
  • Systematic interleave: alternate C,T,C,T down the plate. Cheap, spreads position drift evenly, but the pattern is periodic and can resonate with periodic instrument effects (every 8th well, every column). Use when position drift dominates and batch does not.
  • Replicate bridge: one identical reference aliquot in every batch, measured and subtracted as a per-batch offset. Use when a batch physically can't hold both conditions (shared reagent, single-condition kit). Costs one well per batch and assumes the bridge behaves like the samples.
  • Full randomization, no blocking: fine when the batch effect is known to be small; you give up the ability to separate it cleanly if it turns out not to be.

Case against blocking: it needs the nuisance source named in advance. An operator effect you didn't block stays confounded, and a balanced design gives no protection against a nuisance you didn't anticipate. If a whole batch fails you lose equal numbers of both conditions: good for bias, bad for power.

Failure modes and how you catch them

  • Condition-batch confounding: read the allocation table before running; the symptom is a batch effect that tracks condition exactly. Cost: uninterpretable run.
  • Lane imbalance: count C and T per lane in metadata; a lane with 6 C and 0 T is a confound at lane level.
  • Plate-edge effect: seed a control in edge and center wells and compare; if edge reads differ systematically, randomize positions or exclude edges.
  • Barcode collision: two samples sharing an index in one lane demultiplex into one; check index uniqueness per lane before sequencing. Cost: lost samples.
  • Operator effect: record operator in metadata and check the operator×condition correlation; if one operator ran all treated, you have a confound.
  • Unrecorded rerun: reconcile planned vs actual sample counts per lane; a silent re-run shows up as duplicates or gaps.
  • Randomization broken by convenience: compare planned order to actual load order in the LIMS; bench order is the usual culprit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Diagnose a confounded expression study.

Answer

Short answer. If every treated sample sits in one batch and every control in another, condition and batch are the same variable and the condition effect is not estimable. Diagnose it before fitting anything: build the design matrix, check its rank, and cross-tab condition against batch. No downstream modelling recovers the effect, because the data contain no information that separates the two.

Check the design rank.

R
library(limma)
condition <- factor(c("ctrl","ctrl","trt","trt"))
batch     <- factor(c("A","A","B","B"))
design <- model.matrix(~ condition + batch)
design
#   (Intercept) conditiontrt batchB
# 1           1            0      0
# 2           1            0      0
# 3           1            1      1
# 4           1            1      1
qr(design)$rank      # 2
ncol(design)         # 3
is.fullrank(design)  # FALSE

conditiontrt and batchB are identical columns, so the matrix has rank 2 instead of 3. limma's nonEstimable(design) names the coefficient you cannot estimate. If you fit anyway, limma returns NA for the aliased coefficient and warns Partial NA coefficients for N probe(s). DESeq2 is stricter: DESeq() calls checkFullRank() and errors with the model matrix is not full rank, so the model cannot be fit to the data. Dropping batch from the formula makes the fit succeed, but the condition coefficient is then just the batch difference.

Cross-tab.

Batch ABatch B
Control30
Treated03

A diagonal table is perfect confounding. A single zero cell (3/1 vs 1/3) is only partial confounding: the design is full rank and the effect is estimable, but it is carried by the few off-diagonal samples, so power drops and the estimate is fragile. Worth flagging even when the rank check passes.

Why it is not a modelling problem. In ~ condition + batch the condition coefficient is the treated-minus-control difference after removing batch. When the two factors move together, that adjusted difference is the batch difference; there is no residual variation left to attribute to condition. The estimate is not noisy-but-unbiased, it is undefined. Fitting anyway attributes the batch shift to condition: you get a long list of hits (hypothetically hundreds of genes at padj < 0.05 and |log2FC| > 1) that are pure batch.

What to do. Redesign with condition and batch crossed, each condition in at least two batches: the only clean fix. If the samples are already run, add bridging samples: a few of each condition in the other batch, which breaks the collinearity and makes the effect estimable. Computational correction is not a fix here. ComBat, sva and RUVseq estimate the batch term from variation shared across samples within a batch; under complete confounding that term absorbs the condition effect, so you remove the biology with the artefact. They are reasonable when confounding is partial and a biological covariate is in the model, not when the design is rank-deficient.

Detection and failure modes. Rank check, nonEstimable(), cross-tab, with PCA or clustering as corroboration (samples separating by batch rather than condition). Failure modes: false positives from batch-driven genes; false negatives if you drop batch and lose power; a p-value from an aliased contrast is meaningless. Relabelling samples or deleting the batch term does not fix it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Investigate an RNA-seq sample outlier.

Answer

Core answer (first 90 seconds)

First I'd pin down what "outlier" means here: a sample whose expression profile deviates from the rest of its group by more than the biological spread, in a way the design doesn't explain. Two axes decide everything downstream: technical vs biological, and sample-level vs gene-level.

Assumptions I'd state up front: I know the design (groups, batches, covariates), I have per-sample QC, and I have at least 3 replicates per group.

Order: QC first, structure second, model influence third, decision last.

QC. FastQC/MultiQC per sample: per-base quality, adapter content, rRNA fraction, duplication. Then alignment: STAR unique alignment is typically 75–90% for human poly-A libraries, so a sample at 40% is a technical outlier; salmon/kallisto mapping rate above ~60% is normal. Library size within ~3–4x of the median is unremarkable; 10x off is not. Low input or degraded RNA shows as 3' bias plus high duplication.

Identity. Sex-marker expression is the cheapest swap check: XIST (female) against RPS4Y1/DDX3Y/KDM5D (male). If a sample's markers disagree with its metadata sex, suspect a swap or mislabel. Genotype concordance (verifyBamID, or SNP overlap between samples) confirms it.

Structure. PCA on VST or rlog counts, a sample-sample correlation heatmap, hierarchical clustering. The question is whether the outlier sits alone on PC1/PC2 or whether a whole batch does. One sample off on PC1 with everything else tight is a sample problem; a batch split is a batch problem.

Model influence. DESeq2 flags samples by Cook's distance: with cooksCutoff=TRUE (default) the cutoff is the 0.99 quantile of the F(p, m-p) distribution, and with minReplicatesForReplace=7 (default) samples in groups with at least 7 replicates get their counts replaced rather than dropped. In edgeR, plotMDS (top 500 genes by default) and plotQLDisp show the same thing.

Decision. Technical and correctable → fix and rerun. Technical and not correctable → exclude, documented, against a rule set before looking at results. Biological → keep it and model it (add a covariate, or use RUVseq/sva to estimate the unwanted factor).

Trade-off: exclusion costs power and biases effect sizes when the sample is informative, and the bias is worst when the exclusion is chosen after seeing the DE results. So the rule is fixed in advance, and I report the analysis both with and without the sample.

Failure modes: batch-wide issue (excluding one sample doesn't fix a bad lane), remaining replication below 3 per group, rare biology erased because the outlier was the signal, mislabeled sample retained, undocumented manual choice.

signalnormalflag
STAR unique alignment75–90%<60%
rRNA fraction<5–10%>20%
library sizewithin 3–4x median>10x off
sex markersconcordant with metadatadiscordant → swap
Cook's distancebelow 0.99 F-quantileabove

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

Use PCA to assess an RNA-seq cohort.

Answer

Core answer. PCA on an RNA-seq cohort is a QC step, not a hypothesis test. You want three things from it: do samples group by the biological condition you care about, do they group by a technical covariate you must control for, and does any sample sit far from everything else. The recipe: transform counts so variance is roughly independent of mean, keep the most variable genes, center the samples, plot PC1 vs PC2 colored by condition and shaped by batch, then read the plot against the design sheet, not the other way round.

Why the transform. Raw counts have a mean-variance relationship: a gene with mean 10,000 has variance in the thousands, a gene with mean 5 has variance near 5. PCA maximizes variance, so on raw counts PC1 is dominated by library size and a handful of high-expression genes. DESeq2's vst() fits a dispersion-mean curve and applies it, so transformed variance no longer tracks mean. rlog() does the same via a regularized log but is slower and memory-heavy; the DESeq2 vignette recommends it only for small datasets (roughly n < 30) and vst() above that. log2(CPM + 1) is the cheap fallback (instant, no model fit) but the pseudocount distorts low-count genes and the mean-variance trend survives, so it is a quick look, not the default.

Why top 500 genes, center not scale. DESeq2's plotPCA defaults to the 500 most variable genes (ntop = 500) and calls prcomp(..., center = TRUE, scale. = FALSE). Using all genes lets a few high-variance genes dominate; scaling every gene to unit variance would give a noisy low-count gene the same weight as a real marker. Centering is enough.

Code (R 4.3, DESeq2 1.38).

R
library(DESeq2)
dds <- DESeqDataSetFromMatrix(counts, coldata, design = ~ condition)
keep <- rowSums(counts(dds) >= 10) >= min(table(coldata$condition))
dds <- dds[keep, ]
vsd <- vst(dds, blind = TRUE)                      # default; QC must not see the design
plotPCA(vsd, intgroup = c("condition", "batch"))   # ntop = 500 default

blind = TRUE matters. With blind = FALSE the transformation uses the design, which leaks condition into the QC plot and can manufacture the separation you were trying to check for.

Failure modes and how you catch them.

FailureDetection
Raw counts, PC1 = depthSpearman rho between PC1 scores and colSums(counts) near 1; drops to roughly 0.1 after vst (illustrative figures).
Batch confounded with conditiontable(batch, condition) has empty cells. No transform fixes this: you must redesign or put batch in the model.
Overreading PC2Scree plot shows PC2 at ~8% variance. Permute condition labels, rerun PCA; if the "separation" reappears, it is noise.
Removing a biological axisBefore regressing out a PC, correlate its scores with known covariates (cell type, sex, RIN). High rho means that PC is signal, not batch.
Sample swapTwo aliquots of one subject land in different clusters. PCA flags it; confirm with SNP/genotype concordance, not PCA alone.
Covariates chosen post hocIf the covariate list changed after you saw the plot, the QC is p-hacked. Fix covariates from the design sheet first.

Trade-offs. vst is fast and scales to thousands of samples but needs enough samples to fit the dispersion curve; rlog is better under ~30 samples but slow; log2CPM is instant but leaves the mean-variance trend in place. For a 20-sample cohort, rlog; for 200, vst; for a first look before DESeq2 is set up, log2CPM with the caveat stated.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Handle batch in differential expression and visualization.

Answer

Core answer. Put batch in the design matrix and test condition on the transformed counts; use batch-corrected values only for figures, and label them as corrected. The reason is arithmetic, not taste: correcting before testing strips the batch variance out of the residual, so the test's error term shrinks while the effect estimate stays put, and the t-statistic inflates.

Worked trace. Eight samples, two batches, two conditions, two replicates per cell, log2 expression:

samplebatchconditionlog2 expr
1Actrl5.0
2Actrl5.2
3Atrt6.0
4Atrt6.2
5Bctrl7.0
6Bctrl7.2
7Btrt8.0
8Btrt8.2

Batch shifts every value by +2.0, condition by +1.0. Fit ~ condition alone: the condition estimate is 1.0, but the residuals are the ±1.0 batch offset, giving sigma = 1.16, SE = 0.82, t = 1.22 on 6 df, not significant. Fit ~ batch + condition: same estimate 1.0, residuals now ±0.1, sigma = 0.126, SE = 0.089, t = 11.2 on 5 df. Same data, same effect, a nine-fold difference in SE. The design is balanced here, so the estimate is unchanged; with imbalance the no-batch fit is biased as well.

Code (R, limma):

R
batch <- factor(c("A","A","A","A","B","B","B","B"))
cond  <- factor(c("ctrl","ctrl","trt","trt","ctrl","ctrl","trt","trt"))
design <- model.matrix(~ batch + cond)   # cols: (Intercept), batchB, condtrt
v   <- voom(counts, design)
fit <- eBayes(lmFit(v, design))
topTable(fit, coef = "condtrt")

eBayes moderates each gene's residual variance toward a shared prior, so the per-gene t is shrunk toward the genome-wide trend; the direction of the batch effect above is unchanged. In DESeq2 the same model is design(dds) <- ~ batch + condition, then results(dds, contrast=c("condition","trt","ctrl")) and lfcShrink(..., type="apeglm") for effect sizes.

Visualization. Correct a copy, not the analysis matrix: removeBatchEffect(assay(vst(dds, blind=FALSE)), batch=batch) or sva::ComBat(expr, batch=batch, mod=model.matrix(~cond)). Pass mod so ComBat keeps the condition signal; with mod=NULL it assumes no biology and removes condition too. Label the axis "batch-corrected for display" and never feed those values back into a test.

Alternatives and when. Unknown batch: estimate surrogate variables with sva::svaseq and add them to the design, but they are estimated from the same data, so count their df. Many batch levels: duplicateCorrelation or a mixed model rather than fixed effects. When batch is perfectly confounded with condition (all controls in batch A), the design is rank-deficient: qr(design)$rank < ncol(design) and limma reports coefficients not estimable. No correction recovers that contrast; drop it or re-collect.

Failure modes to check in review. Rank-deficient design (check qr rank); a batch level with one sample, which absorbs that sample and leaves no residual df; double correction (ComBat then removeBatchEffect); hidden batch left in the residual, which shows up as inflated dispersion in plotDispEsts; and correction fitted on all samples including validation, which leaks batch parameters: fit on training only.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Run interpretable pathway enrichment.

Answer

Core answer

First question back: what's the input. A cutoff gene list, or a full ranked list? That decides ORA versus GSEA. Second: what was actually assayed? The universe is the set of genes that could have entered the list, not the genome.

If I have a defensible cutoff (padj < 0.05 and |log2FC| > 1) and a clean tested-gene universe, I run over-representation with Fisher's exact test, BH-adjust across the tested gene sets, and report direction, overlap counts, adjusted p, and the collapsed term set. If the signal is distributed and no cutoff is defensible, I run GSEA on the signed ranking statistic instead.

Why the universe decides the result

ORA asks: given N genes in the universe, K of them in pathway P, and n genes in my list, how surprising is an overlap of k? Expected overlap is nK/N. Inflate N with genes that were never assayed and you shrink that expectation, so every pathway looks enriched, and the winners are the big, well-annotated sets (ribosome, cell cycle, spliceosome) because they carry the largest K.

Worked hypothetical: pathway P has 100 genes genome-wide but only 30 among the 2,000 genes my pipeline actually tested; my list has 50 genes, 10 of them in P.

overlap kgenome background (N=20,000, K=100)tested background (N=2,000, K=30)
10≈8e-14≈3e-9
2≈0.026≈0.17

Same data, same pathway: four orders of magnitude apart at k=10, and at k=2 the wrong background calls it significant while the right one does not. (Binomial approximations, hypothetical numbers.)

Code

R
library(clusterProfiler); library(org.Hs.eg.db)
tested <- rownames(res)[!is.na(res$padj)]        # genes actually tested
sig    <- rownames(subset(res, padj < 0.05 & abs(log2FoldChange) > 1))

eg   <- bitr(sig,    "ENSEMBL", "ENTREZID", org.Hs.eg.db)   # warns on unmapped
univ <- bitr(tested, "ENSEMBL", "ENTREZID", org.Hs.eg.db)

ego <- enrichGO(eg$ENTREZID, universe = univ$ENTREZID, OrgDb = org.Hs.eg.db,
                ont = "BP", pAdjustMethod = "BH",
                pvalueCutoff = 0.05, qvalueCutoff = 0.05, readable = TRUE)
ego <- simplify(ego, cutoff = 0.7, by = "p.adjust", select_fun = min)

Read bitr's unmapped warning. If a fifth of your symbols drop, the result describes the mappable subset, not the biology.

Alternatives

methodinputstrengthcost
ORA (clusterProfiler enrichGO/enrichKEGG)cutoff list + universefast, transparent, easy to reportthreshold-sensitive; background dominates; discards ranking
GSEA (fgsea; MSigDB Hallmark = 50 sets)full signed ranking, e.g. DESeq2 Wald statno cutoff, uses every gene, gives a leading-edge subsetneeds a defensible ranking metric; set-size and gene-length sensitivity
g:Profiler gost()list or ranked listone call across GO/KEGG/Reactome, g:SCS correction for the GO hierarchy, archived releasesless control over the universe

Pick ORA when the cutoff is defensible and the universe is clean; GSEA when the effect is distributed or the cutoff is arbitrary; g:Profiler when you need cross-database coverage with a citable archive ID.

Failure modes and how I'd catch them

  • Wrong universe → recompute with the tested-gene background and diff the ranked list. If the top ten reorders, the first run was an artefact.
  • Stale annotation → pin the release. MSigDB releases are named by year and quarter (2024.1.Hs); KEGG updates continuously, so cite the g:Profiler archive ID or the clusterProfiler run date.
  • Gene-length bias → RNA-seq gives longer genes more reads and more DE power, so long-gene sets (ribosomal, mitochondrial) float up. Detect by length-stratified resampling of the background.
  • Symbol collision → HGNC aliases and retired symbols map many-to-one; check bitr's unmapped count and duplicate ENTREZIDs before trusting the list.
  • Redundant terms → GO BP parent/child pairs; simplify(cutoff = 0.7) collapses them, and you report the collapsed set.
  • Mixed direction → a term can hit because half its genes go up and half go down. Split by sign and re-run, or use a signed GSEA ranking.
  • Cherry-picking → pre-register the contrast and report every term passing FDR, not the three that fit the story.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Interpret an inflammatory tissue signature.

Answer

What I'd say first

Assumptions: bulk RNA-seq (or microarray) of inflamed vs control tissue, no matched single-cell data in hand yet, and the real question is whether a changed marker means more cells or more expression per cell. My answer: a bulk signature is a product, counts ≈ (abundance per cell) × (number of cells) × (RNA content per cell), so before calling anything "inflammatory activation" I decompose it into composition and per-cell expression, and I only claim cellular origin when a matched single-cell or spatial measurement supports it.

The decomposition

For gene g in sample s: bulk expression ≈ Σ_c N_{c,s} · e_{g,c} · r_c, where N is cell count, e is per-cell expression, r is RNA content. Deconvolution tools estimate the N·r term: CIBERSORTx with the LM22 matrix (22 hematopoietic subsets), xCell, MCP-counter, EPIC, quanTIseq. They are not interchangeable. MCP-counter returns relative abundance scores comparable across samples but not fractions; CIBERSORTx returns fractions that sum to 1 plus a deconvolution p-value (I treat p < 0.05 as a floor) and I want estimated fractions to correlate R > 0.7 with matched scRNA-seq before trusting them.

Worked check (hypothetical numbers)

Inflamed vs control tissue, bulk RNA-seq. CD3E goes 40 → 120 TPM, a 3.0× rise. Naive read: T cells are activated. Run CIBERSORTx: T-cell fraction 0.08 → 0.20, a 2.5× rise. Per-cell expression = 3.0 / 2.5 = 1.2×. So roughly 80% of the signal is more T cells, not more expression per T cell. If the fraction had stayed flat at 0.08, the 3.0× would be real per-cell induction. That division is the whole job.

Trade-offs

Deconvolution is cheap, reuses existing bulk, and scales to hundreds of samples, but it needs a signature matrix that matches the tissue, and it resolves types, not states (it will not separate M1 from M2 macrophages). Matched scRNA-seq is ground truth for composition and states, but it is a different aliquot, dissociation biases it (neutrophils and eosinophils are lost, stromal cells survive), and it costs per sample. Do not use deconvolution when no reference matrix fits the tissue, when low-RNA cells (neutrophils) dominate the infiltrate: their mRNA contribution is small relative to their cell count, so they are systematically under-called, or when the question is about cell state rather than abundance.

Failure modes and how I catch them

  • Composition mistaken for regulation: divide bulk fold-change by deconvolution fold-change; if the ratio is ~1, it is composition.
  • Marker non-specificity: PTPRC/CD45 rises with any leukocyte, so it cannot separate T from B; check the marker against a single-cell reference before interpreting.
  • Disease-altered reference: LM22 is built from healthy blood; inflamed macrophages shift state, so residuals rise and fractions stop summing sensibly. Detect by poor correlation with matched scRNA-seq.
  • Spatial heterogeneity: a 3× bulk rise can be one intense focus. Detect with Visium or IHC.
  • Circular marker selection: picking markers from the same dataset you test inflates the signal; pre-register markers from independent data.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

You have bulk RNA-seq from a tissue in two conditions and one gene comes back 2-fold up. How do you estimate the cell-type composition of those samples, and how does that estimate change what you conclude about the condition?

Answer

Bulk counts are a mixture, not a per-cell measurement. For gene g in sample s: reads(g,s) = Σ_k cells(k,s) × RNA_per_cell(k) × expr(g,k). A 2-fold bulk change can come from the first two terms (composition, RNA content) or the third (regulation). So I estimate fractions first, validate them against something that is not RNA, then ask whether the effect survives.

Reference. Two families. Signature-matrix regression: CIBERSORTx fits a signature matrix (LM22 for immune) by nu-SVR on TPM, non-log values. Single-cell-reference methods: MuSiC runs weighted non-negative least squares against an scRNA-seq reference, weighting genes by cross-subject variance. Marker-set scoring (ssGSEA, xCell) gives relative enrichment, not fractions; it ranks samples but cannot support "macrophages went from 10% to 25%". I pick a matched scRNA-seq reference from the same tissue when one exists, otherwise a curated signature matrix, and I say out loud that its profiles came from blood or tumour and may not transfer to this tissue.

Inputs. Deconvolution wants length-normalized, non-log values. I quantify with Salmon against a GENCODE annotation, import with tximport, and hand TPM to the deconvolution; raw counts go to DESeq2 separately. Feeding counts to a TPM-calibrated signature matrix is a silent unit error.

Validation. Orthogonal measurement is the point: flow cytometry or IHC on matched sections, or a matched scRNA-seq sample from the same tissue. Without that, three weaker checks: fractions are non-negative and sum to 1; marker genes for a cell type correlate with its estimated fraction across samples (r ≈ 0.7 or better); two methods with different references agree on direction and rough magnitude. When CIBERSORTx and MuSiC disagree on one cell type, the reference is usually wrong for that type, not the biology subtle.

methodreferenceinputoutputfirst failure
CIBERSORTxsignature matrix (LM22)TPM, non-logfractions summing to 1reference built from blood, applied to tissue
MuSiCscRNA-seq, same tissueTPM or countsfractionsreference missing a cell type
ssGSEA / xCellmarker setsnormalized expressionrelative scorenot a fraction; no cross-sample comparison

Worked trace. Gene X, a macrophage marker. Macrophages express X at 100 TPM per cell-equivalent, epithelium at 5. Condition A is 10% macrophages: 0.10×100 + 0.90×5 = 14.5. Condition B is 25% macrophages: 0.25×100 + 0.75×5 = 28.75. Ratio 1.98. The 2-fold "upregulation" is entirely composition; per-cell expression never moved. Run it backwards: if X were genuinely 2-fold up per cell but macrophage fraction fell from 25% to 10%, bulk would be flat. A real regulatory change hidden by composition.

Interpretation. If the effect is composition, the conclusion is about recruitment, proliferation or loss of a cell type, not a signalling change in the tissue. If it survives composition adjustment, it is regulatory. I add estimated fractions as covariates in the DESeq2 design (~condition + macrophage_fraction) only when composition is a nuisance: different biopsy depth, sampling variation. When composition is downstream of condition, as in inflammation recruiting macrophages, adjusting removes the effect I am trying to report. Then I report both the total effect and the composition-adjusted effect and name which estimand the question is about.

Failure modes worth naming: fractions are RNA-weighted, not cell-number-weighted, so hepatocytes and lymphocytes are not comparable per cell; ambient RNA inflates the dominant type; naive and memory CD4 T cells are collinear and no signature separates them cleanly; disease alters the reference profiles themselves; and picking markers from the same DE list you are testing is circular.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Package a reproducible expression analysis.

Answer

What a strong candidate says first (60–120 s)

"Package" means one directory a reviewer can hand to a clean machine and get the same differential-expression table back. I'd assume bulk RNA-seq, count-based DE (DESeq2 or edgeR), a single cohort, and human samples under a consent agreement. The package pins three layers independently (inputs, environment, code) and treats the design and contrast as data, not as logic buried in a script. If any one layer is unpinned, the result is not reproducible even when the other two are.

The manifest is the package

layerpinned byconcrete form
inputsSHA-256 per filesha256sum *.fastq.gz > checksums.txt
environmentcontainer digest and lockfileimage@sha256:…, renv.lock / conda env export
codegit commitgit rev-parse HEAD recorded in the run log
designcontrast as a filecontrast.tsv with treat,ctrl
outputsimmutable tablescount matrix + results TSV, written once, never edited

A container digest alone is not enough: latest re-pulls a different image. Pin the digest, and keep the lockfile so the environment is reconstructable without the registry.

Why sample order is the failure that matters

Statistical output depends on metadata because the design matrix is built by aligning sample labels to count-matrix columns. If you assign condition by position, rep(c("ctrl","treat"), each = n/2), and the count columns are in a different order than the sample sheet, the labels silently swap. DESeq2 will not error: it fits a valid model with the contrast sign flipped, and every log2 fold change inverts. Detection is a one-line assertion before the model:

R
stopifnot(all(names(condition) == colnames(counts)))

Join by sample ID, never by row index, and assert the join produced no NA.

Trade-offs

Full container pinning gives bit-identical environments but is heavy and hard to audit; a lockfile is lighter and diffable but can resolve differently across OSes. For a cohort of ~20 samples I'd ship the container digest plus lockfile and accept the size. Per-sample packaging isolates one bad library but multiplies provenance overhead; cohort-level packaging is the default unless a sample is re-run. Consent-aware IDs (hashed sample keys, no names in filenames) satisfy the agreement but break naive joins: keep a private ID map outside the package.

Failure modes and how they surface

failuredetection
sample order mismatchthe stopifnot above; contrast sign sanity check
annotation driftpin the GTF/Ensembl release; assert gene count matches
overwritten countschecksum the matrix; write outputs read-only
hidden exclusionlog every filtered sample with a reason
notebook staterun via Snakemake/Nextflow, not a live kernel
dependency updatelockfile diff in CI
private data exposurescan package for raw IDs before sharing
plot detached from tableregenerate figures from the results TSV in the same run

Close

Ship the manifest, the assertion, and the immutable tables. A reviewer should be able to re-run and diff, not read a narrative about what you did.

Curated: · Written: · Reviewed:

Difficulty: Hard