Exercise: Many genes at once — limma
Goal
After this exercise you will be able to:
- Predict the output of
model.matrix(column names, entries, rank) before running it. - Check a design with
qr(X)$rankand explain anNAcoefficient fromlm. - Run a limma analysis of bulk RNA-seq counts with
design = ~ batch + sex + treatment, read log2 fold changes andadj.P.Val, and compare designs against a known truth. - Do the same for log2 intensities from mass-spectrometry metabolomics, with a continuous covariate (BMI).
- Explain why a perfectly confounded design gives “coefficients not estimable”, and why only the experiment can fix it.
Background
A design formula is a recipe for the design matrix \(X\) in \(\mathbf{y} = X\boldsymbol\beta + \boldsymbol\varepsilon\) (see Design matrices for covariates). In R:
| formula term | columns of \(X\) | coefficient means |
|---|---|---|
| intercept (always there) | (Intercept), all 1s |
mean of the reference group |
factor treatment (ctrl, treat) |
treatmenttreat |
treat minus ctrl |
factor batch (A, B, C) |
batchB, batchC |
B minus A, C minus A |
number bmi |
bmi |
change per BMI unit |
- The reference level is the alphabetically first level, unless you change it.
- \(\boldsymbol\beta\) is unique only if
qr(X)$rankequalsncol(X)(the columns are linearly independent). Otherwise there are infinitely many solutions (see Linear systems in R):lmand limma returnNAfor a column. - limma fits every row of a log2-scale omics table with the same \(X\). On the log2 scale each coefficient is a log2 fold change (logFC): 1 = doubled, \(-1\) = halved.
adj.P.Valis the p-value adjusted for testing thousands of genes: among genes called atadj.P.Val < 0.05, about 5% are expected to be false. - If a covariate is unbalanced across the groups you compare, leaving it out of the design mixes its effect into the treatment effect (Confounding & Simpson’s paradox).
By hand
Do these on paper first. Then check each one in R (the code is in the solutions).
B1. Predict model.matrix. Six samples:
| sample | batch | sex | treatment |
|---|---|---|---|
| 1 | A | F | ctrl |
| 2 | A | M | treat |
| 3 | B | F | ctrl |
| 4 | B | M | treat |
| 5 | C | F | treat |
| 6 | C | M | ctrl |
Write the column names of
model.matrix(~ batch + sex + treatment). How many columns are there?Write the full \(6 \times 5\) matrix.
Samples 5 and 6 fail quality control and are removed. Write \(X\) for the four remaining samples. Which two columns are now identical? What are
ncol(X)andqr(X)$rank? Which coefficient doeslmreport asNA?
B2. Confounded batches. Eight samples: samples 1–4 are controls sequenced in batch A, samples 5–8 are treated samples sequenced in batch B.
Write \(X\) for
~ batch + treatment. What is its rank, and how many coefficients are there?What does
lmreturn? What does limma’slmFitsay?Propose a new layout of the same eight samples over the two batches that gives a full-rank \(X\). Which layout is best, and why?
B3. limma coefficients and fold changes. A limma analysis uses design <- model.matrix(~ batch + sex + treatment) with batch (A, B, C), sex (F, M) and treatment (ctrl, treat).
What does
colnames(design)print? Which name do you give totopTable(fit, coef = ...)to get the treatment effect?A colleague writes
topTable(fit, coef = 2). Which comparison does that report? Why is a name safer than a number?A gene has a mean log2 expression of 6.64 in the controls (about 100 on the original scale). Its
logFCfortreatmenttreatis 2. What is its expected value in the treated samples (same batch and sex), on the log2 scale and on the original scale? And if the logFC were \(-1\)?
B4. Reading lm output. For the drug/batch example from Confounding & Simpson’s paradox, R prints:
coef(lm(expr ~ treatment, data = g))
# (Intercept) treatmenttreat
# 17.5 -3.0
coef(lm(expr ~ batch + treatment, data = g))
# (Intercept) batchB treatmenttreat
# 10 10 2From the second model, compute the predicted expression of a control in batch B and of a treated sample in batch A.
In one sentence: why are the two
treatmenttreatcoefficients different, and which one is the drug effect?
B5. A continuous covariate in limma. A limma fit of one metabolite’s log2 intensity with design <- model.matrix(~ group + bmi) gives coefficients (Intercept) 10, groupdisease 1, bmi 0.1.
Predict the log2 intensity for a healthy person with BMI 20 and for a disease patient with BMI 30.
The two differ by 2 on the log2 scale, that is a factor 4. How much of that difference is due to disease and how much to BMI?
In R
Install limma once with BiocManager::install("limma") (see Install R).
R1 — Simulate a bulk RNA-seq experiment
We simulate counts so that we know the truth: 2000 genes, 12 samples in two sequencing batches, F and M samples, controls and treated. Genes 1–200 truly respond to treatment (LFC \(\pm 1.5\)), genes 101–600 differ between batches (LFC \(\pm 2\)), genes 1901–1950 are higher in M. The treatment is unbalanced across batches: batch A has 1 control and 5 treated samples, batch B the opposite.
library(limma)
set.seed(1)
# sample table: one row per sample
samples <- data.frame(
batch = factor(rep(c("A", "B"), each = 6)),
sex = factor(rep(c("F", "M"), times = 6)),
treatment = factor(c("ctrl", rep("treat", 5), rep("ctrl", 5), "treat")))
rownames(samples) <- paste0("s", 1:12)
# true log2 fold changes, one row per gene
n <- 2000
lfc_treat <- rep(0, n); lfc_treat[1:200] <- sample(c(-1.5, 1.5), 200, TRUE)
lfc_batch <- rep(0, n); lfc_batch[101:600] <- sample(c(-2, 2), 500, TRUE)
lfc_sex <- rep(0, n); lfc_sex[1901:1950] <- 3
B <- cbind(lfc_batch, lfc_sex, lfc_treat)
# the same design matrix for every gene
X <- model.matrix(~ batch + sex + treatment, data = samples)
base <- exp(rnorm(n, log(200), 1)) # baseline mean count of each gene
mu <- base * 2^(B %*% t(X[, -1])) # mean count: genes x samples
phi <- 0.05 + 2 / base # negative-binomial dispersion
counts <- matrix(rnbinom(n * 12, mu = mu, size = 1 / phi), nrow = n,
dimnames = list(paste0("g", 1:n), rownames(samples)))
truth_de <- lfc_treat != 0 # TRUE for the 200 DE genesPrint
table(samples$batch, samples$treatment)andX. Check thatXis what you expect.Compute
ncol(X)andqr(X)$rank. Can this design separate batch, sex and treatment?In the line that computes
mu, what doesB %*% t(X[, -1])do? Why is it the sameXfor every gene?
R2 — One gene with lm
Gene g138 is one of the true DE genes (true LFC \(+1.5\)) and is also higher in batch B (true batch LFC \(+2\)). Fit it with lm on the log2 scale:
y <- log2(counts["g138", ] + 1)
coef(lm(y ~ treatment, data = samples))
coef(lm(y ~ batch + sex + treatment, data = samples))Which model gets the treatment effect roughly right? Explain the other one with the table from R1(a).
R3 — limma with the full design
RNA-seq counts are first put on the log2 scale with voom, which also records how noisy each value is (low counts are noisier).
design <- model.matrix(~ batch + sex + treatment, data = samples)
v <- voom(counts, design)
fit <- eBayes(lmFit(v, design))
tt <- topTable(fit, coef = "treatmenttreat", number = Inf)
head(tt)Which coefficient names can you give to
coef =? Did you predict them in B3?Look at
tt["g138", ]. Compare itslogFCwith yourlmestimate in R2 and with the truth.How many genes have
adj.P.Val < 0.05? How many of them are truly DE, and how many are false positives?topTablesorts the genes, so put them back in order first:called <- tt[rownames(counts), "adj.P.Val"] < 0.05, thentable(called, truly_DE = truth_de).
R4 — Leave batch out
Refit with design = ~ treatment (redo voom with the new design) and repeat R3(c).
How many genes are called now, and how many of them are false positives?
Most of the false positives come from one group of genes. Which group? Count them with
lfc_batch != 0.Look at
g138again. What happened?
R5 — A perfectly confounded experiment
Now suppose the lab had put all controls in batch A and all treated samples in batch B:
samples_conf <- samples
samples_conf$treatment <- factor(ifelse(samples$batch == "A", "ctrl", "treat"))
table(samples_conf$batch, samples_conf$treatment)
design_conf <- model.matrix(~ batch + treatment, data = samples_conf)
fit_conf <- lmFit(voom(counts, design_conf), design_conf)
head(fit_conf$coefficients)Read the message. Confirm it with
qr(design_conf)$rank.What does
lm(log2(counts["g1", ] + 1) ~ batch + treatment, data = samples_conf)return fortreatmenttreat?The message disappears if you use
design = ~ treatment. Is that a fix? What would you tell the lab?
R6 — limma on metabolomics data
Mass spectrometry gives log2 intensities directly, so there is no voom step.
We simulate an untargeted mass-spectrometry metabolomics study: log2 intensities of 150 metabolites in 16 people, 8 healthy and 8 with a disease. Covariates: sex, BMI, and the MS run day (a batch). Metabolites 1–20 truly change with disease (log2 difference \(\pm 1\)); metabolites 21–45 rise with BMI (0.15 per BMI unit), 46–55 differ by sex, and every metabolite shifts a little between run days. The disease group has a higher BMI on average, and most patients were measured on day 2.
library(limma)
set.seed(2)
meta <- data.frame(
group = factor(rep(c("healthy", "disease"), each = 8), levels = c("healthy", "disease")),
sex = factor(rep(c("F", "M"), times = 8)),
day = factor(c(1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2)))
meta$bmi <- round(ifelse(meta$group == "disease", 29, 24) + rnorm(16, 0, 2.5))
rownames(meta) <- paste0("p", 1:16)
m <- 150
eff_group <- rep(0, m); eff_group[1:20] <- sample(c(-1, 1), 20, TRUE) # disease
eff_bmi <- rep(0, m); eff_bmi[21:45] <- 0.15 # per BMI unit
eff_sex <- rep(0, m); eff_sex[46:55] <- 1
eff_day <- rnorm(m, 0, 0.7) # run-day shift
X <- model.matrix(~ group + sex + bmi + day, data = meta)
B <- cbind(18 + rnorm(m, 0, 2), eff_group, eff_sex, eff_bmi, eff_day)
logint <- B %*% t(X) + matrix(rnorm(m * 16, 0, 0.4), m) # metabolites x samples
dimnames(logint) <- list(paste0("met", 1:m), rownames(meta))
truth <- eff_group != 0 # the 20 changed metabolitesPrint
table(meta$group, meta$day)andtapply(meta$bmi, meta$group, mean). Which covariates are unbalanced between healthy and disease?Fit the full model and list the top metabolites for disease:
design <- model.matrix(~ group + sex + bmi + day, data = meta)
fit <- eBayes(lmFit(logint, design))
tt <- topTable(fit, coef = "groupdisease", number = Inf)
head(tt)How many metabolites have adj.P.Val < 0.05, and how many of them are among the 20 true ones? Why is the coefficient called groupdisease?
- Repeat (b) with
~ groupand with~ group + sex + day(no BMI). A small helper:
count_hits <- function(f) {
fit <- eBayes(lmFit(logint, model.matrix(f, data = meta)))
tt <- topTable(fit, coef = "groupdisease", number = Inf)
called <- rownames(tt)[tt$adj.P.Val < 0.05]
c(called = length(called), true = sum(called %in% rownames(logint)[truth]))
}
count_hits(~ group)
count_hits(~ group + sex + day)
count_hits(~ group + sex + bmi + day)Which design gives false positives, and which metabolites are they? Why does adding day find more true metabolites, and why does adding bmi remove false ones but also lose some true ones?
DESeq2 on the same counts, and on the real airway dataset, is in the next unit: Bulk RNA-seq with DESeq2.
Hints
Each factor gives one column per level except the reference, which is the alphabetically first level (factor, relevel). The column name is the variable name followed by the level: batchB, sexM. See model.matrix.
In limma, coef = takes a column of the design matrix, by name ("treatmenttreat") or by position. The position depends on the order of the formula, so the name is safer. See topTable.
On the log2 scale you add the logFC. Back on the original scale that multiplies by \(2^{\text{logFC}}\): logFC 1 doubles, 2 quadruples, \(-1\) halves.
A true positive is called and truth_de; a false positive is called and not truth_de. table with two arguments cross-tabulates.
B is genes \(\times\) 3 (one row of true coefficients per gene) and t(X[, -1]) is 3 \(\times\) samples (the columns of \(X\) without the intercept, transposed). Their product is genes \(\times\) samples: entry \((g, s)\) is \(\mathbf{x}_s \cdot \boldsymbol\beta_g\), the linear predictor of gene \(g\) in sample \(s\) (%*%).
lmFit fits one linear model per row, eBayes shares variance information across rows, and topTable lists results for one column of the design, given by its column name in coef =. See the limma User’s Guide, chapter “Linear models overview”.
Solutions
B1. (a) (Intercept), batchB, batchC, sexM, treatmenttreat: 5 columns (references A, F, ctrl).
(Intercept) batchB batchC sexM treatmenttreat
1 1 0 0 0 0
2 1 0 0 1 1
3 1 1 0 0 0
4 1 1 0 1 1
5 1 0 1 0 1
6 1 0 1 1 0
The rank is 5: samples 5 and 6 are the only ones where sex and treatment differ, and that is enough to separate them.
- Without samples 5 and 6, batch C is gone (no
batchCcolumn) andsexM=treatmenttreat= \((0, 1, 0, 1)\): every M is treated and every F is a control.ncol(X)= 4,qr(X)$rank= 3.lmreturnsNAfortreatmenttreat, the later of the two identical columns. (Ifbatchis a factor that still has the level C, R keeps an all-zerobatchCcolumn, which lowers the rank as well.)
b1 <- data.frame(batch = c("A", "A", "B", "B", "C", "C"),
sex = c("F", "M", "F", "M", "F", "M"),
treatment = c("ctrl", "treat", "ctrl", "treat", "treat", "ctrl"))
X <- model.matrix(~ batch + sex + treatment, data = b1)
qr(X)$rank # 5
X4 <- model.matrix(~ batch + sex + treatment, data = b1[1:4, ])
ncol(X4); qr(X4)$rank # 4 3
coef(lm(c(5, 9, 7, 11) ~ batch + sex + treatment, data = b1[1:4, ]))
# (Intercept) batchB sexM treatmenttreat
# 5 2 4 NAB2. (a)
(Intercept) batchB treatmenttreat
1-4 1 0 0
5-8 1 1 1
batchB = treatmenttreat, so the rank is 2 for 3 coefficients: infinitely many solutions.
lmgivesNAfortreatmenttreat; itsbatchBestimate is batch and treatment together.lmFitdoes the same and prints “Coefficients not estimable: treatmenttreat”.Any layout where both batches contain both conditions gives rank 3. The best is balanced: 2 controls and 2 treated in each batch. Then batch and treatment are not related at all, and the treatment effect is estimated as precisely as possible.
B3. (a) "(Intercept)", "batchB", "batchC", "sexM", "treatmenttreat". Use coef = "treatmenttreat".
Column 2 is
batchB, socoef = 2reports batch B vs A, not the treatment. If someone reorders the formula, the position of every column changes, but the nametreatmenttreatstill points to the treatment.On the log2 scale: \(6.64 + 2 = 8.64\). On the original scale: \(100 \times 2^2 = 400\). With logFC \(-1\): \(6.64 - 1 = 5.64\), that is \(100 \times 2^{-1} = 50\).
B4. (a) Control in batch B: \(10 + 10 = 20\). Treated in batch A: \(10 + 2 = 12\). (These are the data values.)
- The treated samples are mostly in the low batch A and the controls mostly in the high batch B, so
~ treatmentmixes the batch difference into the treatment column; the adjusted model compares within batches, and +2 is the drug effect.
B5. (a) Healthy, BMI 20: \(10 + 0.1 \cdot 20 = 12\). Disease, BMI 30: \(10 + 1 + 0.1 \cdot 30 = 14\).
- Disease contributes 1 and the 10 extra BMI units contribute \(0.1 \cdot 10 = 1\). Half of the log2 difference of 2 is BMI, not disease.
All numbers below are from running the code above (R 4.5, limma 3.60).
R1. (a)
table(samples$batch, samples$treatment)
# ctrl treat
# A 1 5
# B 5 1X has the columns (Intercept), batchB, sexM, treatmenttreat: batchB is 0 for s1–s6 and 1 for s7–s12, sexM alternates 0, 1, and treatmenttreat is 1 for s2–s6 and s12.
ncol(X)= 4 andqr(X)$rank= 4: full rank. Each batch has both conditions, so the design can separate batch and treatment, even though it is unbalanced.Row \(g\) of
Bholds gene \(g\)’s true coefficients (batch, sex, treatment), and column \(s\) oft(X[, -1])holds sample \(s\)’s dummy values. The product is the linear predictor of every gene in every sample. The samples are the same for all genes, so the same \(X\) is used for every row; only the coefficients differ between genes.
R2.
coef(lm(y ~ treatment, data = samples))
# (Intercept) treatmenttreat
# 7.98 -0.24
coef(lm(y ~ batch + sex + treatment, data = samples))
# (Intercept) batchB sexM treatmenttreat
# 6.20 2.29 -0.37 1.41The adjusted model gives 1.41, close to the true 1.5 (and batchB 2.29, close to the true 2). Without batch, the gene looks slightly down (\(-0.24\)): 5 of the 6 treated samples are in batch A, where this gene is low, and 5 of the 6 controls are in batch B, where it is high. That is Simpson’s paradox.
R3. (a) The column names of design: "(Intercept)", "batchB", "sexM", "treatmenttreat".
tt["g138", ]
# logFC AveExpr t P.Value adj.P.Val
# g138 1.34 8.12 4.15 6.6e-05 0.0010logFC 1.34, close to the lm estimate 1.41 and the truth 1.5.
called <- tt[rownames(counts), "adj.P.Val"] < 0.05
table(called, truly_DE = truth_de)
# truly_DE
# called FALSE TRUE
# FALSE 1789 23
# TRUE 11 177188 genes are called: 177 true positives (of 200 DE genes) and 11 false positives (6%, close to the promised 5%).
R4.
design1 <- model.matrix(~ treatment, data = samples)
tt1 <- topTable(eBayes(lmFit(voom(counts, design1), design1)),
coef = "treatmenttreat", number = Inf)
hits1 <- match(rownames(tt1)[tt1$adj.P.Val < 0.05], rownames(counts))
length(hits1); sum(truth_de[hits1]); sum(!truth_de[hits1])
# [1] 304
# [1] 150
# [1] 154
sum(!truth_de[hits1] & lfc_batch[hits1] != 0)
# [1] 151304 genes are called, but 154 are false positives: half of the list is wrong. It also finds fewer true genes (150 instead of 177).
151 of the 154 false positives are batch-affected genes. Because treatment is unbalanced across batches, a pure batch difference looks like a treatment difference.
g138: logFC \(-0.16\),adj.P.Val0.90. The real up-regulation is hidden by the batch effect and the gene is missed.
R5. (a)
Coefficients not estimable: treatmenttreat
# (Intercept) batchB treatmenttreat
# g1 8.94 0.50 NA
# g2 10.16 -1.17 NA
qr(design_conf)$rank is 2 for 3 columns: batchB and treatmenttreat are identical. (voom prints the message too, because it fits the model once internally.)
coef(lm(log2(counts["g1", ] + 1) ~ batch + treatment, data = samples_conf))
# (Intercept) batchB treatmenttreat
# 8.56 0.77 NANA: the 0.77 is batch and treatment together.
- No. With
~ treatmentlimma runs, but every “treatment effect” also contains the batch effect, and there is no way to tell how much of it is batch. The data simply do not contain the information. Tell the lab to redesign the experiment: put controls and treated samples in every batch, ideally balanced (here 3 + 3 per batch), or sequence everything in one batch.
R6. (a)
table(meta$group, meta$day)
# 1 2
# healthy 6 2
# disease 2 6
tapply(meta$bmi, meta$group, mean)
# healthy disease
# 24.00 29.25Run day and BMI are both unbalanced: most patients were measured on day 2 and they have a BMI about 5 units higher. Sex is balanced (4 F and 4 M in each group).
colnames(design)
# [1] "(Intercept)" "groupdisease" "sexM" "bmi" "day2"
head(tt, 4)
# logFC AveExpr t P.Value adj.P.Val
# met4 1.69 15.34 5.05 2.0e-06 0.00030
# met15 1.55 15.91 4.62 1.1e-05 0.00086
# met3 1.45 20.51 4.17 6.5e-05 0.00275
# met2 1.37 16.44 4.14 7.3e-05 0.00275
sum(tt$adj.P.Val < 0.05)
# [1] 1212 metabolites are called, and all 12 are true. The coefficient is groupdisease because healthy was set as the first level, so the column is “disease vs healthy”. (The top estimates, such as 1.69 for met4 whose true value is 1, are larger than the truth: the most significant hits tend to be the ones whose noise happened to push them up.)
count_hits(~ group)
# called true
# 28 15
count_hits(~ group + sex + day)
# called true
# 39 19
count_hits(~ group + sex + bmi + day)
# called true
# 12 12| design | called | true | false |
|---|---|---|---|
~ group |
28 | 15 | 13 |
~ group + sex + day |
39 | 19 | 20 |
~ group + sex + bmi + day |
12 | 12 | 0 |
- Without
bmi, most false positives are the BMI metabolites (met21–45): the patients have a higher BMI, so a BMI effect looks like a disease effect. For example met33 has disease logFC 1.0 (adj.P.Val0.005) withoutbmi, but 0.21 (adj.P.Val0.85) with it. - Adding
dayremoves the run-day shifts from the noise, so every test gets more power: more true metabolites (19), but also more BMI false positives (20). - Adding
bmiremoves the false positives. But BMI and disease are correlated, so the model has less information to tell them apart and some true metabolites are lost (12 of 20). The cure for that is again the design: recruit patients and controls with similar BMI and spread them over the run days.
Where this leads
- Bulk RNA-seq with DESeq2 (next unit): the same designs on the raw counts, size factors, and why fold changes of small counts are noisy.
- Penalized linear models (Why penalize?): when \(X\) has more columns than samples, the rank condition fails by shape, and a penalty is one way to still get a unique \(\boldsymbol\beta\).
- Interactions (
~ sex + treatment + sex:treatment) and contrasts between any two levels (limma’smakeContrasts) use the same design matrix. We do not cover them further here. - limma’s
eBayes(and DESeq2’s dispersion estimate) share information between genes. That is the same idea as the shrinkage in Hierarchical models (week 4). - Error models (week 4): why raw counts need a Poisson or negative-binomial model, which is what DESeq2 uses.