Lesson 1 of 4
Module 4 · RNA-seq analysis
Now a real, published experiment: airway smooth muscle cells from four donors, treated with dexamethasone or not (Himes et al., 2014). Its reads were aligned to the human genome and counted per gene, the same kind of processing as Omics, Bioinformatics and AI, Module 5, lessons 4 and 5 . You will load its counts from Bioconductor, check it, filter it, see why normalisation is needed, and look at the samples with PCA before testing anything.
Install Bioconductor packages
Module 3, Figures that tell the truth, gave you honest, accessible figures and ended with remaking a published one. This module puts everything from the course to work on a real experiment: RNA sequencing of human airway cells treated with a steroid. You will explore the data, test thousands of genes at once with DESeq2 and turn the results into figures and a short written summary. This first lesson covers the data themselves: what a count matrix is, why samples must be normalised, and how to check the samples before any test is run.
Bioconductor is a collection of R packages for analysing biological data, separate from CRAN, the main R package archive. Its packages are released together twice a year and tested to work with each other, so they are installed with their own installer rather than with install.packages().
install.packages("BiocManager")
BiocManager::install(c("airway", "DESeq2", "apeglm", "org.Hs.eg.db"))
install.packages("ggrepel")What this does
install.packages("BiocManager")installs, from CRAN, the small package that installs everything else from Bioconductor.BiocManager::install(...)installs four Bioconductor packages. The::calls a function from a package without loading the whole package first. airway holds the data for this module; DESeq2 does the statistics; apeglm provides the fold-change shrinkage used in Differential expression with DESeq2; org.Hs.eg.db is a database of human gene identifiers, used in Volcano plot and interpretation to turn gene IDs into gene names.install.packages("ggrepel")installs, from CRAN, the package that keeps text labels on plots from overlapping.
You run this block once per computer, not every session. It can take several minutes, because each package brings others it depends on. If R asks whether to update existing packages, answering "none" is a safe choice while you work through the course.
Load and check
An RNA-seq experiment has two parts that must agree: the count matrix (genes in rows, samples in columns) and the sample sheet (samples in rows), which Bioconductor calls colData.
Each number in the count matrix is the number of sequencing reads from one sample that were assigned to one gene. These are whole numbers, and they are the raw material for everything that follows. The sample sheet says what each sample is: here, which donor the cells came from and whether they were treated. The analysis only makes sense if column 1 of the matrix and row 1 of the sheet describe the same sample, column 2 and row 2 the next, and so on.
Why raw counts, and not something already adjusted? Many files you will meet hold values such as TPM or FPKM, which are counts already scaled for sequencing depth and gene length. The statistical model in Differential expression with DESeq2 works on the counts themselves, because it needs to know how many reads lie behind each number: 5 reads out of 10 is far less certain than 5,000 out of 10,000, although the proportion is the same. A count matrix that contains decimals, or values that are all well below 1, has almost certainly been transformed and should not be given to DESeq2.
library(airway)
library(SummarizedExperiment)
library(DESeq2)
data("airway")
counts <- assay(airway) # the count matrix
coldata <- as.data.frame(colData(airway)) # the sample sheet
dim(counts)
coldata[, c("cell", "dex")]
all(colnames(counts) == rownames(coldata))What this does, line by line
- The three
library()calls load the data package, the SummarizedExperiment package (which defines the container the data come in) and DESeq2. data("airway")loads an object calledairway. It is a SummarizedExperiment: one object that holds the count matrix, the sample sheet and information about the genes together, so they cannot drift apart.assay(airway)pulls out the count matrix and stores it ascounts.colData(airway)pulls out the sample sheet;as.data.frame()turns it into an ordinary data frame, stored ascoldata.dim(counts)prints the matrix's dimensions: rows (genes), then columns (samples).coldata[, c("cell", "dex")]shows every row of the sample sheet but only two of its columns.all(colnames(counts) == rownames(coldata))compares the sample names in the two places, position by position.==gives one TRUE or FALSE per sample, andall()returns TRUE only if every one is TRUE.
dim(counts) reports about 64,000 genes and 8 samples; the exact number depends on the package version. The sample sheet records four donors (cell), each with one sample treated with the steroid dexamethasone (trt) and one untreated (untrt). The final TRUE confirms the columns of the count matrix are in the same order as the rows of the sample sheet. If it is ever FALSE, stop.
The row names beginning SRR are run accession numbers from the Sequence Read Archive, the public database where the raw reads are stored; anyone can download the reads under these names. The four cell names identify the four donors' cell lines. Dexamethasone is a synthetic glucocorticoid, a drug that acts like the body's own cortisol. It enters cells and binds the glucocorticoid receptor, a protein that then switches particular genes on or off, which is why its effects show up in RNA. Corticosteroids are widely used to treat asthma, one reason their effects on airway cells are of interest.
The reason to stop at FALSE: if the order differs, the analysis will happily attach the "treated" label to an untreated sample. Nothing will crash, and the results will be wrong in a way that is very hard to spot later.
In Data frames and files you read a version of this sample sheet from a file and turned dex into a factor. With your own data, the counts and the sheet often arrive as separate files in different orders. Reorder one to match the other by name, for example coldata <- coldata[colnames(counts), ], and then run the all() check again. Reordering by name, never by position, is what makes the check pass for the right reason.
One more quick look is worth taking before anything else. colSums(counts) adds up each column, giving each sample's library size: the total number of reads counted for that sample. Differences of up to two or three times are normal and are exactly what normalisation, later in this lesson, corrects. A sample with a tiny fraction of the reads of the others is a warning sign: it may have failed in the laboratory, and its counts will be much noisier.
The airway data are from Himes et al. 2014, PLOS ONE, which studied the response of human airway smooth muscle cells to dexamethasone and reported CRISPLD2 as a glucocorticoid-responsive gene; cite it alongside citation("airway"). The median-of-ratios normalisation in this lesson was introduced in Anders & Huber 2010, "Differential expression analysis for sequence count data" (Genome Biology), and carried into DESeq2. Bioconductor packages are released together twice a year, so report the Bioconductor release, printed by BiocManager::version(), as well as each package version. The exact number of genes in airway can change between package versions, so give the figure from your own run.
Build the dataset and filter
coldata$dex <- relevel(coldata$dex, ref = "untrt")
dds <- DESeqDataSetFromMatrix(countData = counts,
colData = coldata,
design = ~ cell + dex)
keep <- rowSums(counts(dds) >= 10) >= 4 # 10+ reads in 4+ samples
dds <- dds[keep, ]
nrow(dds)What this does, line by line
relevel(coldata$dex, ref = "untrt")makes "untrt" the reference level of the treatment factor: the baseline that the other level is compared with. Fold changes are then reported as treated relative to untreated, so a positive number means higher after treatment.DESeqDataSetFromMatrix()packs the counts, the sample sheet and the design formula into one DESeq2 object,dds. The design~ cell + dexsays that a gene's counts may depend on the donor and on the treatment; Differential expression with DESeq2 explains why both are included.counts(dds) >= 10asks, for every gene in every sample, "at least 10 reads?", giving a TRUE/FALSE matrix.rowSums()counts the TRUEs in each row, because R treats TRUE as 1 and FALSE as 0.>= 4then keeps a gene only if at least 4 of the 8 samples passed.dds[keep, ]keeps those genes and drops the rest.nrow(dds)prints how many genes remain.
Why 4 samples? The smallest group in this design has 4 samples (4 treated, 4 untreated). A gene expressed only in treated cells could have reads in only those 4, so requiring 4 keeps it. Requiring all 8 would throw away exactly the genes that are switched on by treatment.
Notice too that the filter uses only the counts and ignores the treatment labels. It asks "is this gene expressed at all?", not "does this gene look different between groups?". A filter that looked at the groups, for example keeping genes whose treated mean is much higher than their untreated mean, would choose genes because they already look changed and make the later tests overconfident. The cut-off of 10 reads is a common choice, not a fixed rule.
Most genes in the annotation are not expressed in airway muscle cells, so filtering removes a large share. Removing them speeds up the analysis and reduces the number of tests later.
Worked example · why normalise: size factors by hand
Samples are sequenced to different depths. DESeq2 corrects with the median-of-ratios method. Three genes, two samples, where sample 2 was simply sequenced twice as deeply:
A 100 200 √(100×200) = 141.4 0.71 1.41
B 50 100 √(50×100) = 70.7 0.71 1.41
C 300 600 √(300×600) = 424.3 0.71 1.41
size factor = median ratio → S1 0.71, S2 1.41
gene A: 100 ÷ 0.71 = 141 and 200 ÷ 1.41 = 141
Step by step. The geometric mean of n numbers is the nth root of their product; for two numbers it is the square root. For gene A: 100 × 200 = 20,000, and √20,000 = 141.4. Each sample's count is then divided by that gene's geometric mean: 100 ÷ 141.4 = 0.71 and 200 ÷ 141.4 = 1.41. Genes B and C give the same ratios. A sample's size factor is the median of its ratios across all genes, so S1 is 0.71 and S2 is 1.41. Dividing each count by its sample's size factor gives the normalised counts.
What the answer means. Using the median makes the method robust: in a real experiment, a few hundred genes truly change, but the median ratio is set by the thousands that do not. If one gene went up tenfold, its ratio would be an outlier and the median would barely move.
After normalisation, gene A is the same in both samples, which is right: the only difference was depth. DESeq2 does this for you, so always give it raw counts.
Go deeper: size factors in the real data, and the zero problem
The worked example used three tidy genes. In real data many genes have a count of 0 in at least one sample. Their geometric mean is then 0 and the ratios cannot be calculated, so DESeq2 leaves those genes out and takes each sample's median over the genes counted in every sample. In airway that is still about 18,900 of the 63,677 genes in the package.
You can look at the result yourself: dds <- estimateSizeFactors(dds); sizeFactors(dds) prints one number per sample. For airway they run from about 0.67 to 1.40, so the deepest sample was sequenced roughly twice as deeply as the shallowest. If almost every gene contains a zero, as in single-cell data, this method breaks down, which is why single-cell tools normalise differently. DESeq() reuses size factors that are already present, so calling this step early does no harm.
Why not simply divide each sample by its library size? Because the total can be distorted by a few genes. Imagine one sample in which a handful of very highly expressed genes doubles. Those genes take a larger share of a fixed number of reads, so every other gene receives fewer, and dividing by the total would make thousands of unchanged genes look lower in that sample. This is called composition bias. The median-of-ratios method avoids it because the median ignores the few genes that changed and follows the many that did not.
Once size factors are estimated, counts(dds, normalized = TRUE) returns the counts divided by them. These normalised counts are good for plots and for comparing one gene across samples, as in the single-gene plot of Volcano plot and interpretation. They are not good input for DESeq2 itself, which applies the size factors inside its model and needs the raw counts beside them. Size factors correct only for depth and composition between samples; they do not make different genes comparable with each other, because a longer gene collects more reads at the same level of expression.
Look before you test: PCA
Counts are noisy at low values. The variance-stabilising transformation, vst(), puts them on a scale suited to PCA and heatmaps. PCA then places each sample by its overall expression pattern, so you can see what drives the biggest differences.
Some detail on both. With raw counts, a gene's variance grows with its mean: genes with thousands of reads swing by hundreds, genes with a few reads by a few. The VST is roughly a log transformation, adjusted so that low counts are not exaggerated, after which a gene's spread no longer depends much on its level. Principal component analysis (PCA) then summarises thousands of genes in a few new axes. The first, PC1, is the direction along which the samples differ most; PC2 is the next largest direction at right angles to it. Each axis is labelled with the percentage of the total variation it captures.
Why not just take log2(counts + 1)? It is a reasonable first idea, and it does tame the very large counts. But for genes with only a few reads, the log greatly enlarges small random differences: a gene with 0 reads in one sample and 3 in another differs by 2 on the log2 scale, as much as a gene going from 1,000 to 4,000 reads. In a PCA those noisy low-count genes then add spread that is not biology. The VST uses the dispersion trend DESeq2 estimates from the data to shrink exactly those low-count differences, while behaving like an ordinary log2 for well-expressed genes.
PCA itself is easiest to understand with two genes. Plot every sample by its value for gene 1 and gene 2, and the points form a cloud. PC1 is the line through the cloud along which the points are most spread out; PC2 is the line at right angles to it. With thousands of genes the same idea applies in thousands of dimensions, and PCA finds the few directions that capture most of the differences between samples.
library(ggplot2)
library(pheatmap)
vsd <- vst(dds, blind = TRUE)
pca <- plotPCA(vsd, intgroup = c("dex", "cell"), returnData = TRUE)
pv <- round(100 * attr(pca, "percentVar"))
ggplot(pca, aes(PC1, PC2, colour = dex, shape = cell)) +
geom_point(size = 3.5) +
scale_colour_manual(values = c(untrt = "#0F1B33", trt = "#D9481F")) +
labs(x = paste0("PC1: ", pv[1], "% variance"),
y = paste0("PC2: ", pv[2], "% variance")) +
theme_minimal(base_size = 13)
# how similar is each sample to every other?
sample_dists <- dist(t(assay(vsd)))
pheatmap(as.matrix(sample_dists),
clustering_distance_rows = sample_dists,
clustering_distance_cols = sample_dists,
annotation_col = coldata[, c("dex", "cell")])What this does, block by block
vst(dds, blind = TRUE)applies the transformation.blind = TRUEmeans it ignores the design, so the treatment labels cannot influence what you see: right for a first, unbiased look.plotPCA(vsd, intgroup = c("dex", "cell"), returnData = TRUE)runs the PCA (by default on the 500 genes that vary most across samples) and, because ofreturnData = TRUE, returns a data frame of coordinates instead of drawing a plot, with thedexandcellcolumns attached.attr(pca, "percentVar")reads the share of variation captured by each component, stored as an attribute of that data frame. Multiplying by 100 and rounding gives whole percentages,pv.- The
ggplot()block draws one point per sample, coloured by treatment (navy untreated, vermilion treated) and shaped by donor.paste0()joins text and numbers into the axis titles, such as "PC1: " followed by the percentage. dist(t(assay(vsd)))computes the distance between every pair of samples across all genes.dist()measures distances between rows, so the matrix is first transposed to put samples in rows.pheatmap(...)draws those distances as an 8 × 8 heatmap, clustered by the same distances, with treatment and donor shown as coloured bars.
What to look for. Treated and untreated samples should separate along one axis: the treatment is the largest effect. Samples from the same donor tend to sit close together on another axis, which is the donor effect the paired design will account for.
In the distance heatmap, the same pattern appears as blocks. Each sample has a distance of 0 to itself, so the diagonal shows the lowest value on the colour scale; samples of the same treatment, or the same donor, form blocks of small distances. The two views are a check on each other.
Read the percentages on the axes too. They say how much of the total variation each component captures among the genes used. A large PC1 percentage with clean separation by treatment means the treatment dominates the data. If PC1 instead separates one sample from all the others, that sample is an outlier and deserves attention before you go further.
When a sample looks wrong, investigate before acting. A sample that sits with the treated group but is labelled untreated may simply be mislabelled. Check its library size from colSums(counts) and any notes from the laboratory too. Remove a sample only for a reason you can state, such as a failed library, and report that you did. Dropping samples because they do not fit the expected pattern makes the results look cleaner than the experiment really was.
Key point
Always explore before testing. A PCA that shows one sample far from all others, or groups that do not separate at all, changes how you should run and trust the analysis.
A second example: in a study run over two weeks, the PCA separates samples by the day they were processed rather than by treatment. That is a batch effect, a technical difference that swamps the biology. Seen early, it can be added to the design, as donor is here; missed, it can produce a list of "treatment" genes that are really "day" genes.
Further reading · Module 4Love, Huber & Anders 2014: the method, and why it shrinks fold changes. · All reading for this course
Check your understanding
1. Two samples have size factors 0.5 and 1.0, and a gene has raw counts 100 and 200. After normalisation?
2. Why apply vst() before PCA?
3. What should you give DESeq2?
Up next
Lesson 2
Differential expression with DESeq2