LSMA

LONDON SCHOOL OF MULTIOMICS & AI

LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 31 lessons

Batch effects and design formulas

Batch effects and design formulas

Batch effects and design formulas

Samples processed in batches can differ for reasons that have nothing to do with biology. This lesson finds a batch in a PCA, writes it into the design formula, and shows why you model it rather than remove it.

This lesson follows Importing Salmon and kallisto counts, which ended with a count matrix ready for DESeq2. Before testing any gene, it is worth asking what else, apart from the treatment, might have made the samples differ.

What a batch effect is

A batch effect is a difference between groups of samples that comes from how they were handled, not from the biology you want to study. Samples prepared on different days, by different people, with different kits, or sequenced on different machines or in different runs can all differ in ways that touch thousands of genes at once. None of this is anyone's fault. It is a normal part of laboratory work, and the question is only whether the analysis can tell it apart from the effect of interest.

Whether it can depends on the design of the experiment, not on the software. Compare two layouts for four treated and four control samples run in two batches:

  • Balanced: each batch holds two treated and two control samples. Within every batch, treated and control can be compared directly, so the batch difference can be estimated and set aside.
  • Confounded: all treated samples in batch 1 and all controls in batch 2. Every difference between the groups is also a difference between the batches. No statistical method can say how much is treatment and how much is batch, because the data contain no sample where the two differ.

The lesson is simple and worth repeating to anyone planning an experiment: spread every condition across every batch. A balanced design costs nothing extra at the bench, and it is the only real protection. Once samples have been run in a confounded layout, no amount of analysis recovers the answer.

The pasilla data, installed with the pasilla Bioconductor package, show a mild, real example. The experiment knocked down the pasilla gene in fruit fly cells with RNA interference and compared them with untreated cells. Some libraries were sequenced as single-end reads (one read per fragment) and some as paired-end (one read from each end). The library type is a technical difference that could shift counts gene by gene, and it is spread across both conditions.

R
library(DESeq2)
library(ggplot2)
library(limma)

dir    <- system.file("extdata", package = "pasilla")
counts <- as.matrix(read.delim(file.path(dir, "pasilla_gene_counts.tsv"),
                               row.names = "gene_id"))
anno   <- read.csv(file.path(dir, "pasilla_sample_annotation.csv"), row.names = 1)

rownames(anno) <- sub("fb$", "", rownames(anno))
coldata <- data.frame(
  condition = factor(anno$condition, levels = c("untreated", "treated")),
  libtype   = factor(ifelse(anno$type == "paired-end", "paired", "single")),
  row.names = rownames(anno))
coldata <- coldata[colnames(counts), ]
all(rownames(coldata) == colnames(counts))
table(coldata$condition, coldata$libtype)

What this does

  • system.file("extdata", package = "pasilla") finds the folder of example files inside the installed package, so the code works on any computer.
  • read.delim(..., row.names = "gene_id") reads the tab-separated count table with the fly gene IDs as row names; as.matrix() turns it into the plain numeric matrix DESeq2 expects. It has 14,599 genes and 7 samples.
  • read.csv(..., row.names = 1) reads the sample annotation. Its sample names end in "fb" (for example "treated1fb") while the count columns do not, so sub("fb$", "", ...) removes those two letters; the $ means "only at the end".
  • The data.frame() keeps two columns: condition, a factor with untreated as the first level, and libtype, recoded to the short labels "paired" and "single". Short labels without hyphens keep the coefficient names readable later.
  • coldata[colnames(counts), ] puts the rows in the order of the count columns, by name. The all() check from RNA-seq counts and exploration prints TRUE.
  • table() cross-tabulates the two factors. This one line is the most useful check of any design.
[1] TRUE paired single untreated 2 2 treated 2 1

Every condition appears with both library types, so the design is not confounded. It is not perfectly balanced either, with one treated single-end sample, but that is enough for a model to separate the two effects.

Spotting batch in a PCA

The PCA from RNA-seq counts and exploration is the first place a batch effect shows itself. Colour the points by condition and give them shapes by the suspected batch; if the shapes form their own groups, the batch is moving many genes.

R
dds  <- DESeqDataSetFromMatrix(counts, coldata, design = ~ libtype + condition)
keep <- rowSums(counts(dds) >= 10) >= 3      # 3 = the smallest group
dds  <- dds[keep, ]

vsd <- vst(dds, blind = TRUE)
pca <- plotPCA(vsd, intgroup = c("condition", "libtype"), returnData = TRUE)
pv  <- round(100 * attr(pca, "percentVar"))

ggplot(pca, aes(PC1, PC2, colour = condition, shape = libtype)) +
  geom_point(size = 3.5) +
  scale_colour_manual(values = c(untreated = "#0072B2", treated = "#E69F00")) +
  labs(x = paste0("PC1: ", pv[1], "% variance"),
       y = paste0("PC2: ", pv[2], "% variance")) +
  theme_minimal(base_size = 13)
pca[, c("PC1", "PC2", "condition", "libtype")]
PC1 PC2 condition libtype untreated1 -8.356376 6.240880 untreated single untreated2 -8.380695 3.726951 untreated single untreated3 -6.296471 -6.543830 untreated paired untreated4 -6.085945 -6.316613 untreated paired treated1 7.921716 10.031597 treated single treated2 10.566627 -2.605348 treated paired treated3 10.631144 -4.533637 treated paired

The filter keeps 8,148 genes. PC1 captures 57% of the variance and splits the samples cleanly by condition: every untreated sample is negative, every treated one positive. PC2 captures 30%, and it follows library type: the single-end samples all have positive PC2 values, the paired-end samples all negative. The knockdown is the largest effect, and library type is the second. That is a batch effect worth modelling, even though it does not hide the biology.

A PCA can also suggest a batch you did not record. If samples fall into two groups that match neither condition nor any column of your sample sheet, go back to the laboratory notes: dates, operators, kit lot numbers and sequencing runs are the usual culprits. Add whatever explains the split to the sample sheet, so it can enter the design.

Model the batch, do not remove it

A tempting idea is to "clean" the counts of batch first and then run DESeq2 on the cleaned values. Do not. DESeq2 needs raw counts, as RNA-seq counts and exploration explained, and a corrected matrix is no longer a matrix of counts. Instead, put the batch in the design formula, exactly as the donor went into ~ cell + dex for airway. The model then estimates a batch effect for every gene alongside the treatment effect, and tests the treatment with the batch held fixed. The uncertainty in the batch estimate is carried into the standard errors, which a separate cleaning step would hide.

R
model.matrix(~ libtype + condition, data = coldata)

dds <- DESeq(dds)
resultsNames(dds)
res <- results(dds, contrast = c("condition", "treated", "untreated"), alpha = 0.05)

dds_naive <- DESeqDataSetFromMatrix(counts, coldata, design = ~ condition)[keep, ]
dds_naive <- DESeq(dds_naive)
res_naive <- results(dds_naive, alpha = 0.05)

sum(res_naive$padj < 0.05, na.rm = TRUE)
sum(res$padj < 0.05, na.rm = TRUE)
median(res_naive$lfcSE, na.rm = TRUE); median(res$lfcSE, na.rm = TRUE)
(Intercept) libtypesingle conditiontreated untreated1 1 1 0 untreated2 1 1 0 untreated3 1 0 0 untreated4 1 0 0 treated1 1 1 1 treated2 1 0 1 treated3 1 0 1 … [1] "Intercept" "libtype_single_vs_paired" [3] "condition_treated_vs_untreated" [1] 853 [1] 1108 [1] 0.1582371 [1] 0.1374142

Worked example · reading the model matrix

The model matrix is how R turns a formula into numbers: one row per sample, one column per coefficient. A 1 means "this coefficient applies to this sample". For each gene, the model's expected log2 expression in a sample is the sum of the coefficients marked 1 in its row:

untreated3 (paired, untreated): Intercept
untreated1 (single, untreated): Intercept + libtypesingle
treated2 (paired, treated): Intercept + conditiontreated
treated1 (single, treated): Intercept + libtypesingle + conditiontreated

Step by step. The intercept is the baseline: paired-end and untreated, because "paired" and "untreated" are the first levels of their factors. libtypesingle is the shift for single-end libraries, the same in both conditions. conditiontreated is the shift for knockdown, the same in both library types. Treated1 gets both shifts added together.

What the answer means. The treatment coefficient is estimated by comparing treated with untreated samples of the same library type, so a library-type difference cannot leak into it. This additive model assumes the knockdown moves a gene by the same amount in both library types; the interaction term below relaxes that.

Adding libtype raises the number of genes with padj < 0.05 from 853 to 1,108, and 842 genes are found by both. The median standard error of the log2 fold changes falls from 0.158 to 0.137. That is the gain from modelling a batch: variation that the naive model counted as noise is explained, so each treatment estimate is more precise. The pasilla gene itself, FBgn0261552, has a log2 fold change of about −1.87, a fall to roughly a quarter, as a knockdown should; its padj is 3.1 × 10−20 without library type in the model and 3.5 × 10−33 with it.

Modelling a batch is not free. Each extra factor level uses up one degree of freedom, a unit of information from the samples. With seven samples and three coefficients there is plenty left, but a design with many batches and few samples can end up less powerful than a simpler one. Include factors that the PCA or the laboratory notes give you a reason to include, not every column of the sample sheet.

Removing batch for a picture only

For figures, though, a batch-corrected matrix is useful: a PCA or heatmap that shows the biology without the batch. limma::removeBatchEffect() does this on the transformed values.

R
mat    <- assay(vsd)
mm     <- model.matrix(~ condition, data = coldata)
mat_rb <- removeBatchEffect(mat, batch = coldata$libtype, design = mm)

vsd_rb <- vsd
assay(vsd_rb) <- mat_rb
pca_rb <- plotPCA(vsd_rb, intgroup = c("condition", "libtype"), returnData = TRUE)
round(100 * attr(pca_rb, "percentVar"))[1:2]

What this does

  • assay(vsd) takes the variance-stabilised values, which are roughly on a log2 scale, the scale removeBatchEffect() is built for.
  • design = mm tells the function which effect to protect: the condition. Without it, part of the knockdown effect could be removed along with the batch, because the batches are not perfectly balanced.
  • The corrected matrix is placed in a copy of vsd, so plotPCA() can be used exactly as before.

The output is [1] 82 13: PC1 now captures 82% of the variance, still separating untreated from treated, and PC2 drops to 13% and no longer splits the samples by library type. Use mat_rb for figures, and say in the legend that library type was removed for display. Never pass it, or any other corrected matrix, to DESeq2.

The grammar of design formulas

A design formula starts with ~ and lists the variables that may affect each gene's counts, joined by +. A few rules cover most experiments.

  • Nuisance first, interest last: ~ batch + condition. The order does not change the fitted model, but DESeq2 reports the last variable by default when no contrast is named. Naming the contrast, as above, is safer still.
  • Reference levels come from the order of factor levels. Here untreated and paired are first, so fold changes are treated versus untreated, and libtype_single_vs_paired is single relative to paired. Set them with factor(..., levels = ) or relevel(), as for dex in airway.
  • Interactions, written a:b, let the effect of one variable depend on the other. ~ libtype + condition + libtype:condition asks whether the knockdown effect differs between library types.
  • Full rank means no column of the model matrix can be built from the others. A confounded design breaks this rule, and DESeq2 stops.

The pasilla data contain a confounded subset, which shows the error. Take the two paired-end treated samples and the two single-end untreated ones:

R
sub <- c("treated2", "treated3", "untreated1", "untreated2")
coldata[sub, ]
DESeqDataSetFromMatrix(counts[, sub], coldata[sub, ],
                       design = ~ libtype + condition)
condition libtype treated2 treated paired treated3 treated paired untreated1 untreated single untreated2 untreated single Error in checkFullRank(modelMatrix) : the model matrix is not full rank, so the model cannot be fit as specified. One or more variables or interaction terms in the design formula are linear combinations of the others and must be removed. …

In these four samples, "single" and "untreated" always occur together, so the libtypesingle column of the model matrix is identical to "1 minus conditiontreated". DESeq2 refuses to guess. Dropping libtype from the design would let the code run, but it would not fix anything: the treatment comparison would still be a library-type comparison too. The honest report is that these samples cannot separate the two.

The same error appears for other reasons worth knowing: a factor level with no samples left after subsetting (fix with droplevels()), or two columns of the sample sheet that record the same thing under different names.

Go deeper: testing an interaction in pasilla

With the design ~ libtype + condition + libtype:condition, resultsNames() adds a fourth coefficient, libtypesingle.conditiontreated. It is the extra knockdown effect in single-end libraries compared with paired-end ones. Testing it with results(dds_int, name = "libtypesingle.conditiontreated", alpha = 0.05) gave one gene with padj < 0.05 out of 8,148. So library type shifts genes, but it barely changes how they respond to the knockdown, which supports the simpler additive design.

Be careful reading other coefficients in a model with an interaction. condition_treated_vs_untreated is then the knockdown effect in the reference library type only, paired-end, not an average over both. With only one treated single-end sample, the interaction is also estimated from very little data; interactions need replicates in every combination to be estimated well.

Common mistakes

  • Correcting counts before DESeq2. Running ComBat, removeBatchEffect() or any other correction and then feeding the result to DESeq2 breaks its count model. Put the batch in the design.
  • Batch as a number. If batches are recorded as 1, 2 and 3, R treats the column as a continuous number with a straight-line effect. Convert it with factor() first.
  • Using the corrected PCA as evidence. A PCA after removeBatchEffect() shows what you asked it to show. Report the uncorrected PCA as your check of the data.
  • Silencing a full-rank error by dropping a variable. The error is a message about the experiment, not the code.
  • Adding every sample-sheet column. Each factor costs degrees of freedom. Include batches the data or the notes point to.

Leek et al. 2010, "Tackling the widespread and critical impact of batch effects in high-throughput data" (Nature Reviews Genetics), surveys how batch effects arise and why balanced designs matter. The pasilla data come from Brooks et al. 2011 (Genome Research); cite the package with citation("pasilla"). removeBatchEffect() is part of limma, described in Ritchie et al. 2015 (Nucleic Acids Research). For count data where a batch truly cannot be modelled in the design, ComBat-seq (Zhang, Parmigiani & Johnson 2020, NAR Genomics and Bioinformatics) adjusts counts while keeping them whole numbers; report clearly if you use it.

Key point

A batch effect is handled by design at the bench and by the design formula in R. Spread conditions across batches, look for batch in the PCA, and model it with ~ batch + condition. Remove it only to draw pictures.

In pasilla, modelling library type found about 250 more significant genes and made the fold changes more precise, without touching the counts. The next lesson, Differential expression with DESeq2, runs the same kind of model on airway, where the "batch" is the donor.

Further reading · Module 4Love, Huber & Anders 2014: the method, and why it shrinks fold changes. · All reading for this course

Check your understanding

1. All treated samples were sequenced in run 1 and all controls in run 2. What can DESeq2 do about the run?

2. Why is library type added to the pasilla design as ~ libtype + condition instead of removing it from the counts first?

3. What is limma::removeBatchEffect() appropriate for in an RNA-seq analysis?

Ask LSMA