Skip to contents

A reproducible, gene-level RNA-seq workflow: eight airway smooth-muscle samples, four donors, dexamethasone versus control. Raw reads are quantified against the reference transcriptome with salmon, imported with tximeta, and tested with DESeq2. Every figure below is produced by the code shown next to it.

How to reproduce. The upstream, compute-heavy half (§2) is documented and runnable but not executed when this page is knitted. The analysis half (§3 onward) runs end to end in a couple of minutes on a laptop. Set params$source to "quants" to point it at your own salmon directories instead of the bundled counts.


Design and provenance

Four primary human airway smooth-muscle cell lines were each split into a treated and an untreated aliquot, then exposed to 1 µM dexamethasone for 18 hours (Himes et al. 2014). That paired structure is the single most important fact about this dataset, and it drives the design formula used throughout:

~ cell + dex

The dex term is the effect of interest; cell absorbs the donor-to-donor differences so they do not inflate the residual variance. Ignoring cell would cost real power, as §4.4 makes visible.

Experiment GEO GSE52778, SRA SRP033351
Runs SRR1039508/09/12/13/16/17/20/21
Donors N61311, N052611, N080611, N061011
Treatment 1 µM dexamethasone, 18 h, vs. untreated
Reference GENCODE human transcripts
Quantifier salmon, selective alignment, GC-bias correction
**Figure 1. The full workflow, bench to result.** Panels 1--5 are the wet-lab steps described in [the bench section](#bench); panel 6 is the computational pipeline implemented from [Import](#import) onward. Created with BioRender.

Figure 1. The full workflow, bench to result. Panels 1–5 are the wet-lab steps described in the bench section; panel 6 is the computational pipeline implemented from Import onward. Created with BioRender.

The figure above is drawn for a wheat root experiment, which is the application this repository was assembled for. The worked example carried through the rest of the document is the airway dataset, because it is small, public and packaged – but every step maps one-to-one onto panels 1–6, and Adapting this to your own data sets out what to change to run your own.

suppressPackageStartupMessages({
  # containers and import
  library(SummarizedExperiment)
  library(tximeta)
  library(DESeq2)
  # transformation, distances, ordination
  library(vsn)
  library(PoiClaClu)
  library(glmpca)
  # plotting
  library(ggplot2)
  library(pheatmap)
  library(RColorBrewer)
  library(ggbeeswarm)
  # shrinkage, annotation, genomic plots
  library(apeglm)
  library(AnnotationDbi)
  library(org.Hs.eg.db)
})
#> Error in get(paste0(generic, ".", class), envir = get_method_env()) : 
#>   object 'type_sum.accel' not found

theme_set(
  theme_bw(base_size = 12) +
    theme(
      panel.grid.minor = element_blank(),
      panel.border     = element_rect(colour = "grey70", fill = NA),
      strip.background = element_rect(fill = "grey95", colour = "grey70"),
      plot.title       = element_text(face = "bold", size = 13),
      legend.position  = "right"
    )
)

# A consistent two-colour treatment palette and a four-colour donor palette,
# both colour-blind safe.
pal_dex  <- c(untrt = "#4C72B0", trt = "#DD8452")
pal_cell <- c("#55A868", "#C44E52", "#8172B3", "#937860")

Rendered with R 4.4.2 and DESeq2 1.46.0.


From tissue to reads: the bench steps

Panels 1–5 of Figure 1. None of this is executed by the pipeline, but the decisions made here constrain everything downstream, and a count matrix cannot repair a library built on degraded RNA. Each subsection ends with the sources worth reading before you commit to a protocol.

What each panel means

The figure uses terms that are standard in sequencing and opaque outside it. Taken panel by panel:

1. Root sampling. Transcription does not stop when tissue is cut. Genes respond to wounding, light and temperature within minutes, so the profile you measure drifts away from the one you meant to capture for as long as the tissue stays warm. Liquid nitrogen at -196 °C stops enzyme activity almost instantly and holds the transcriptome where it was at the moment of harvest.

2. RNA extraction. Plant cells have walls, so they must be broken mechanically: the frozen tissue is ground to a powder under liquid nitrogen, which also keeps it from thawing. The powder goes into a lysis buffer that denatures the RNases which would otherwise degrade the RNA within seconds of release. In a phase extraction the mixture separates into two layers, drawn in panel 2: RNA stays in the upper aqueous phase, while protein and most DNA move to the organic phase and the interface between them. DNase is then added to destroy any genomic DNA that carried over, because fragments of genomic DNA map to exons and would be counted as though they were transcripts.

3. RNA quality control. Two separate questions: how much RNA there is, and how intact it is. The trace in panel 3 plots fragment size against abundance. The two sharp peaks are ribosomal RNA, 18S and 25S – these are structural RNAs of the ribosome, not messages, and they dominate total RNA by mass. Intact RNA gives two clean peaks; degraded RNA gives a smear, because the molecules have been chopped into fragments of every length. Note that plants show 18S and 25S where a mammalian sample would show 18S and 28S, which is why software tuned to mammalian traces can score a perfectly good plant sample badly.

4. Library preparation. This is where the sample becomes something a sequencer can read, and it is the densest panel.

  • mRNA is messenger RNA: the transcribed copy of a gene that carries the instructions for a protein. It is what you want to measure. It is also a small fraction of total RNA, typically a few per cent, with ribosomal RNA making up most of the rest.
  • Poly(A) is a tail of many adenine (A) bases added to the end of most mature mRNAs. Ribosomal RNA does not carry one. That difference is the handle the next step uses.
  • Oligo(dT) magnetic beads are beads coated with short stretches of thymine (T) bases. Because T pairs with A, the beads bind poly(A) tails and nothing much else. A magnet holds the beads against the tube wall while the unbound ribosomal RNA is washed away. This is what “poly(A) selection” means: not that the mRNA is purified chemically, but that it is fished out by its tail.
  • Fragmented RNA: sequencers read short stretches, not whole molecules, so the captured mRNA is cut into pieces of a few hundred bases.
  • cDNA synthesis: reverse transcriptase copies each RNA fragment into complementary DNA. DNA is stable and can be amplified; RNA is neither.
  • Indexed library: short known sequences, the adapters, are attached to both ends. One of them carries an index, a barcode unique to the sample, so that many samples can be pooled in one sequencing run and sorted out again afterwards. The coloured ends in panel 4 are those adapters.
  • Check library size and concentration confirms the fragments came out the intended length and that there is enough material to sequence. A library that is too short, too long or too dilute fails on the instrument.

5. Sequencing. The flow cell is a glass slide carrying a lawn of short DNA probes. Library fragments bind to it, each is copied into a dense local cluster of identical molecules, and the instrument then reads the sequence one base at a time, imaging a fluorescent signal from every cluster in parallel. The output is FASTQ: for each read, the base sequence plus a per-base quality score recording how confident the instrument was in each call.

6. Bioinformatics. Read QC removes adapter sequence and low-quality reads. The reads are then matched against the wheat reference – either aligned to the genome, or, as in this workflow, assigned to reference transcripts by salmon. Counting how many fragments fall to each gene in each sample gives the gene count matrix drawn in panel 6: genes as rows, samples as columns. DESeq2 then asks, gene by gene, whether the difference in counts between conditions is larger than the variability between replicates would predict. The heatmap and volcano plot summarise the answer.

Bread wheat adds a complication at the mapping step that most organisms do not have. It is hexaploid, carrying three related subgenomes (A, B and D), so each gene usually exists as three similar copies called homoeologs. Short reads often match all three. Paired-end reads and a transcriptome-aware quantifier that distributes multi-mapping reads probabilistically, rather than discarding them, both help considerably.

Sampling and preservation

Harvest, then snap-freeze in liquid nitrogen and keep the tissue frozen until it is in lysis buffer. Transcript abundances shift within minutes of excision, particularly stress-responsive genes, so thaw-refreeze cycles silently introduce a treatment-correlated artefact when handling order tracks the treatment groups. Randomise harvest order across groups, and record it.

For root work specifically, decide in advance whether you are profiling the host alone or host and microbiome together; the two need different depletion chemistries and different library strategies.

Further reading. Cevher-Keskin et al. (2025) report a wheat dehydration-shock experiment with leaf and root sampling, and give a concrete account of the tissue-to-transcriptome path in Triticum aestivum. Sainz et al. (2024) review host–microbe designs, including dual RNA-seq, where host and bacterial RNA are sequenced from the same tissue.

RNA extraction

Grind frozen, extract total RNA, then remove genomic DNA with DNase. The DNase step is not optional for quantification: carried-over genomic DNA maps to exons and inflates counts unevenly across samples, and the inflation is not constant, so it does not cancel in a ratio.

Silica-column kits lyse in guanidinium isothiocyanate, which denatures RNases on contact, then bind RNA to a membrane in ethanol and wash the impurities through. Where the DNase goes is a real choice: on-column, while the RNA is bound, or in solution after elution, which costs some yield. Roots are the awkward case, because polysaccharides and polyphenols co-precipitate with RNA and inhibit downstream enzymology, so a standard lysis buffer alone is often not enough.

Further reading. The PureLink RNA Mini Kit user guide (Thermo Fisher Scientific 2012) is a worked example of the column chemistry: guanidinium lysis, silica binding, and both DNase routes – on-column or in solution after purification. For plant tissue it specifies up to 250 mg of fresh or frozen material, ground under liquid nitrogen with mortar and pestle, with lysis volume scaled to mass; and for tissue rich in polyphenolics or starch it directs you to a dedicated plant reagent rather than the standard buffer.

RNA quality control

Measure concentration and integrity, and treat them as separate gates. Automated electrophoresis gives an integrity score on a 1–10 scale: RIN on the Bioanalyzer, RINe on the TapeStation.

Integrity scoring is the part to watch on plant material. The algorithms were built around the mammalian 18S/28S trace, and in green tissue chloroplast and mitochondrial rRNA add peaks of their own, so a perfectly good sample can score misleadingly low. Inspect the electropherogram rather than accepting the number alone.

Further reading. The Agilent automated-electrophoresis compendium (Agilent Technologies, n.d.) covers the Bioanalyzer, TapeStation, Fragment Analyzer and Femto Pulse systems and the metrics each reports. It recommends a RINe of 8.0 or higher for RNA-seq library preparation, and describes DV200, the percentage of fragments above 200 nucleotides, as the metric to use for degraded or FFPE input where an integrity score is no longer meaningful. Cevher-Keskin et al. (2025) applied a RIN >= 8.0 threshold in the wheat study.

Library preparation

Two decisions matter more than the rest.

Enrichment. Poly(A) selection, drawn in panel 4 and described above, is the default for host gene expression. Ribosomal depletion instead removes rRNA and retains non-polyadenylated transcripts, which is what you need for bacterial RNA, many long non-coding RNAs, and degraded input where poly(A) tails may be detached from the body of the transcript.

Strandedness. Use a directional protocol. The dUTP method marks the second cDNA strand so it can be selectively destroyed, leaving a library in which read orientation reports the strand of origin. Without it you cannot resolve antisense transcription or assign reads unambiguously where genes overlap on opposite strands – and you must then tell the quantifier that the library is unstranded, or the counts will be wrong.

Further reading. The NEB technical note for the NEBNext Ultra II Directional RNA Library Prep Kit (New England Biolabs 2023) documents the poly(A) enrichment workflow, the dUTP basis of its directionality, and an input range of 10 ng to 1 µg of total RNA. Note that despite its file name, this note covers poly(A) enrichment; NEB publishes rRNA depletion performance separately. The Illumina method guide (Illumina, Inc. 2025) sets out the parallel decision as three named workflows – mRNA-Seq, total RNA-Seq with Ribo-Zero Plus, and targeted RNA-Seq – with the input requirement for each.

Sequencing: depth and read length

Depth and read length are experimental design parameters, not defaults.

For differential expression of annotated genes, more biological replicates beat more reads per replicate once depth is adequate: the Illumina method guide plans mRNA-Seq around roughly 25 million reads per sample and total RNA-Seq around 50 million, the latter higher because non-coding and residual rRNA consume a share of the output (Illumina, Inc. 2025). Read length follows the question: 2 x 75 bp suffices for counting genes, while isoform-level work and anything involving novel transcripts benefits from longer paired reads.

Paired-end is worth the cost for a polyploid genome such as hexaploid wheat, where the homoeologous A, B and D subgenomes are similar enough that single-end reads are frequently ambiguous between them.


Upstream: reads to transcript abundances

This section is eval=FALSE. It documents exactly how the quantifications were produced, so the numbers downstream are traceable. The same steps are wired up as a Snakemake workflow in workflow/, which is the version to actually run.

Retrieving the reads

prefetch followed by fasterq-dump is faster and far more robust over a slow link than fasterq-dump alone. All eight runs come to roughly 22 GB gzipped.

for SRR in SRR1039508 SRR1039509 SRR1039512 SRR1039513 \
           SRR1039516 SRR1039517 SRR1039520 SRR1039521; do
  prefetch --max-size u --output-directory data/fastq "$SRR"
  fasterq-dump --progress --threads 4 --split-3 \
               --outdir data/fastq "data/fastq/$SRR"
  pigz -f "data/fastq/${SRR}_1.fastq" "data/fastq/${SRR}_2.fastq"
done

Building the index

Two details matter. --gencode strips the pipe-delimited extras from GENCODE FASTA headers, leaving bare ENST identifiers, without which the transcript-to-gene mapping later fails. And a decoy-aware index, built from the genome alongside the transcriptome, measurably reduces spurious mappings of reads whose true origin is intergenic or intronic (Srivastava et al. 2020).

REL=49
BASE=https://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_${REL}

curl -fsSL -O ${BASE}/gencode.v${REL}.transcripts.fa.gz
curl -fsSL -O ${BASE}/GRCh38.primary_assembly.genome.fa.gz

# decoy names = genome sequence names; gentrome = transcripts then genome
zcat GRCh38.primary_assembly.genome.fa.gz \
  | grep '^>' | cut -d ' ' -f1 | tr -d '>' > decoys.txt
cat gencode.v${REL}.transcripts.fa.gz \
    GRCh38.primary_assembly.genome.fa.gz > gentrome.fa.gz

salmon index --gencode -t gentrome.fa.gz -d decoys.txt \
             -i gencode.v${REL}_salmon_index -k 31 -p 6

Quantifying

salmon quant -i data/index/gencode.v49_salmon_index -l A -p 6 \
             --gcBias --seqBias --numGibbsSamples 20 \
             -o data/quants/SRR1039508 \
             -1 data/fastq/SRR1039508_1.fastq.gz \
             -2 data/fastq/SRR1039508_2.fastq.gz

-l A detects the library type automatically. --gcBias and --seqBias estimate correction factors for biases that are present in most real libraries (Love, Hogenesch, and Irizarry 2016; Patro et al. 2017); leave them on unless you have a reason not to. --numGibbsSamples writes posterior samples, which are optional here but useful for uncertainty-aware downstream tools.

Or, preferably, the whole thing at once:

snakemake -j 4 --use-conda --latency-wait 60 \
          --configfile workflow/config.yaml --snakefile workflow/Snakefile

Why quantify rather than align and count

Three concrete gains over aligning to the genome and counting overlaps: changes in effective gene length across samples (differential isoform usage) are corrected for; the step is much faster and needs far less disk; and reads that map to several homologous genes are apportioned rather than discarded (Soneson, Love, and Robinson 2015; Robert and Watson 2015; Trapnell et al. 2013).

Further reading. If you would rather not maintain a quantification workflow at all, nf-core/rnaseq is the community-curated production alternative (nf-core community 2026; Ewels et al. 2020). Its output documentation is worth reading even if you never run it: it enumerates the QC artefacts a mature pipeline is expected to emit – FastQC before and after trimming, rRNA contamination estimates, duplication and library-complexity metrics, strand inference, coverage uniformity – gathered into a single MultiQC report. The salmon route used here corresponds to its salmon/ and star_salmon/ outputs, so the two are directly comparable.


Import

From quant.sf to a gene-level SummarizedExperiment

tximeta reads the salmon output, recognises the reference transcriptome from its checksum, and attaches the matching annotation automatically, so the object knows which genome build it is on. That provenance is what makes the genomic plots in §8 safe to draw.

The chunk below is the one place the two modes diverge. With params$source == "quants" it imports your own quantifications; otherwise it demonstrates the import on the two salmon directories bundled in the airway package and then proceeds with the full eight-sample counts from the same package.

library(airway)

if (identical(params$source, "quants")) {

  stopifnot(
    "coldata file not found - run the Snakemake workflow first" =
      file.exists(params$coldata)
  )
  coldata <- read.csv(params$coldata, stringsAsFactors = FALSE)
  stopifnot(
    "coldata needs 'names' and 'files' columns" =
      all(c("names", "files") %in% colnames(coldata)),
    "some quant.sf files are missing" = all(file.exists(coldata$files))
  )

  se  <- tximeta(coldata)                 # transcript level
  gse <- summarizeToGene(se)              # gene level
  gse$cell <- factor(gse$cell)
  gse$dex  <- factor(gse$dex, levels = c("untrt", "trt"))

} else {

  # --- demonstration of the import itself, on two bundled samples ----------
  dir <- system.file("extdata", package = "airway", mustWork = TRUE)
  demo <- read.csv(file.path(dir, "sample_table.csv"),
                   row.names = 1, stringsAsFactors = FALSE)[1:2, ]
  demo$names <- demo$Run
  # bundled quant files are gzipped to keep the data package small
  demo$files <- file.path(dir, "quants", demo$names, "quant.sf.gz")
  stopifnot(all(file.exists(demo$files)))

  se_demo <- tryCatch(
    tximeta(demo),
    error = function(e) {
      message("tximeta could not reach its annotation sources: ",
              conditionMessage(e),
              "\nContinuing with the bundled gene-level counts.")
      NULL
    }
  )
  if (!is.null(se_demo)) {
    cat("transcript-level dimensions:", dim(se_demo), "\n")
    se_demo_gene <- summarizeToGene(se_demo)
    cat("gene-level dimensions:      ", dim(se_demo_gene), "\n")
  }

  # --- the full eight-sample object ---------------------------------------
  data(gse)
  gse$cell <- gse$donor
  gse$dex  <- gse$condition
  levels(gse$dex) <- c("untrt", "trt")   # order is preserved, names change
  gse$dex  <- relevel(gse$dex, "untrt")  # reference level = untreated
}
#> transcript-level dimensions: 205870 2
#> gene-level dimensions:       58294 2

gse
#> class: RangedSummarizedExperiment 
#> dim: 58294 8 
#> metadata(6): tximetaInfo quantInfo ... txomeInfo txdbInfo
#> assays(3): counts abundance length
#> rownames(58294): ENSG00000000003.14 ENSG00000000005.5 ... ENSG00000285993.1
#>   ENSG00000285994.1
#> rowData names(1): gene_id
#> colnames(8): SRR1039508 SRR1039509 ... SRR1039520 SRR1039521
#> colData names(5): names donor condition cell dex

Renaming factor levels and re-levelling are different operations and it is worth keeping them straight. levels(x) <- c(...) relabels in place and must preserve order. relevel() changes which level is the reference, which changes how contrasts are coded and would flip the sign of the fold change here.

What is in the object

assayNames(gse)
#> [1] "counts"    "abundance" "length"
round(colSums(assay(gse, "counts")) / 1e6, 1)   # library sizes, millions
#> SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516 SRR1039517 SRR1039520 SRR1039521 
#>       21.1       19.3       26.1       15.7       25.3       31.9       19.7       21.8
colData(gse)[, c("cell", "dex")]
#> DataFrame with 8 rows and 2 columns
#>                cell      dex
#>            <factor> <factor>
#> SRR1039508  N61311     untrt
#> SRR1039509  N61311     trt  
#> SRR1039512  N052611    untrt
#> SRR1039513  N052611    trt  
#> SRR1039516  N080611    untrt
#> SRR1039517  N080611    trt  
#> SRR1039520  N061011    untrt
#> SRR1039521  N061011    trt

Three assays: counts (estimated fragments per gene), abundance (TPM) and length (effective gene lengths, which absorb both bias and isoform-usage effects). DESeq2 uses counts for testing and length as an offset.

A critical constraint, and the reason pre-normalised values must never be substituted here: DESeq2’s model needs un-normalised counts to estimate measurement precision. It handles library-size differences internally.

rowRanges(gse)[1:3]
#> GRanges object with 3 ranges and 1 metadata column:
#>                      seqnames              ranges strand |            gene_id
#>                         <Rle>           <IRanges>  <Rle> |        <character>
#>   ENSG00000000003.14     chrX 100627109-100639991      - | ENSG00000000003.14
#>    ENSG00000000005.5     chrX 100584802-100599885      + |  ENSG00000000005.5
#>   ENSG00000000419.12    chr20   50934867-50958555      - | ENSG00000000419.12
#>   -------
#>   seqinfo: 25 sequences (1 circular) from hg38 genome
seqinfo(rowRanges(gse))
#> Seqinfo object with 25 sequences (1 circular) from hg38 genome:
#>   seqnames seqlengths isCircular genome
#>   chr1      248956422      FALSE   hg38
#>   chr2      242193529      FALSE   hg38
#>   chr3      198295559      FALSE   hg38
#>   chr4      190214555      FALSE   hg38
#>   chr5      181538259      FALSE   hg38
#>   ...             ...        ...    ...
#>   chr21      46709983      FALSE   hg38
#>   chr22      50818468      FALSE   hg38
#>   chrX      156040895      FALSE   hg38
#>   chrY       57227415      FALSE   hg38
#>   chrM          16569       TRUE   hg38

Constructing the DESeqDataSet

dds <- DESeqDataSet(gse, design = ~ cell + dex)
dds
#> class: DESeqDataSet 
#> dim: 58294 8 
#> metadata(7): tximetaInfo quantInfo ... txdbInfo version
#> assays(3): counts abundance avgTxLength
#> rownames(58294): ENSG00000000003.14 ENSG00000000005.5 ... ENSG00000285993.1
#>   ENSG00000285994.1
#> rowData names(1): gene_id
#> colnames(8): SRR1039508 SRR1039509 ... SRR1039520 SRR1039521
#> colData names(5): names donor condition cell dex

Had you only a count matrix and a sample table, the entry point is DESeqDataSetFromMatrix() instead:

dds <- DESeqDataSetFromMatrix(
  countData = round(assay(gse, "counts")),   # must be integers
  colData   = colData(gse),
  design    = ~ cell + dex
)

If you take that route, verify by eye that the columns of the count matrix are in the same order as the rows of the sample table. A silent mismatch here produces a confident, wrong answer. Building from a SummarizedExperiment avoids the problem entirely, because subsetting keeps the two in step.


Quality assessment and exploratory analysis

Two distinct paths run through this workflow. Here we transform the counts to explore sample relationships; in §5 we go back to the raw counts for testing. That separation is deliberate, not stylistic: the tests need untransformed counts to model the mean-variance relationship.

Pre-filtering

Rows that are nearly all zero carry no information about differential expression but do cost memory, time, and multiple-testing burden. A count of 10 in at least as many samples as the smallest group is a sound default for bulk RNA-seq.

smallest_group <- min(table(dds$dex))
keep <- rowSums(counts(dds) >= 10) >= smallest_group
cat(sprintf("smallest group: %d samples\n%d of %d genes retained (%.1f%%)\n",
            smallest_group, sum(keep), length(keep), 100 * mean(keep)))
#> smallest group: 4 samples
#> 16637 of 58294 genes retained (28.5%)
dds <- dds[keep, ]

Stabilising the variance

Clustering and PCA assume roughly constant variance across the dynamic range. Count data violates that badly: variance grows with the mean. Simulated Poisson counts make the problem and the fix visible.

lambda <- 10^seq(-1, 2, length.out = 1000)
cts    <- matrix(rpois(1000 * 100, lambda), ncol = 100)

op <- par(mfrow = c(1, 2))
meanSdPlot(cts, ranks = FALSE)                  # raw counts

meanSdPlot(log2(cts + 1), ranks = FALSE)        # naive log

par(op)

Raw counts fan out to the right; the naive log over-corrects and inflates the variance of the smallest values, which then dominate any distance measure. DESeq2 offers two transformations that flatten the trend properly: the variance-stabilising transformation (vst) and the regularised log (rlog).

Which to use: vst is much faster and more robust to high-count outliers, so prefer it for n>30n > 30. rlog can do better on small datasets with a wide range of sequencing depth. With eight samples we compute both and compare.

vsd <- vst(dds,  blind = FALSE)
rld <- rlog(dds, blind = FALSE)
assay(vsd)[1:3, 1:4]
#>                    SRR1039508 SRR1039509 SRR1039512 SRR1039513
#> ENSG00000000003.14  10.082167   9.828058  10.152774   9.970690
#> ENSG00000000419.12   9.663489   9.900634   9.779942   9.775148
#> ENSG00000000457.13   9.417376   9.280001   9.333639   9.430438

blind = FALSE means the design is used to estimate the global dispersion trend, not to transform individual values. It does not bias the comparison of interest. Use blind = TRUE only for a genuinely unsupervised look.

dds <- estimateSizeFactors(dds)

mk <- function(m, label) {
  d <- as.data.frame(m[, 1:2])
  colnames(d) <- c("x", "y")
  d$transformation <- label
  d
}
df <- rbind(
  mk(log2(counts(dds, normalized = TRUE)[, 1:2] + 1), "log2(x + 1)"),
  mk(assay(vsd)[, 1:2], "vst"),
  mk(assay(rld)[, 1:2], "rlog")
)
df$transformation <- factor(df$transformation,
                            levels = c("log2(x + 1)", "vst", "rlog"))

ggplot(df, aes(x, y)) +
  geom_hex(bins = 80) +
  scale_fill_viridis_c(option = "mako", direction = -1) +
  coord_fixed() +
  facet_grid(. ~ transformation) +
  labs(x = "sample 1", y = "sample 2", fill = "genes",
       title = "The same two samples under three transformations")

Low-count genes, bottom left, are wildly variable on the naive log scale and compressed by both vst and rlog. It is the deviation from y=xy = x that feeds the distances and the PCA, so that compression is exactly what we want.

Sample-to-sample distances

sampleDists      <- dist(t(assay(vsd)))   # genes as dimensions, samples as rows
sampleDistMatrix <- as.matrix(sampleDists)
rownames(sampleDistMatrix) <- paste(vsd$dex, vsd$cell, sep = " - ")
colnames(sampleDistMatrix) <- NULL

pheatmap(sampleDistMatrix,
         clustering_distance_rows = sampleDists,
         clustering_distance_cols = sampleDists,
         col  = colorRampPalette(rev(brewer.pal(9, "Blues")))(255),
         main = "Euclidean distance on VST data")

Passing sampleDists explicitly matters. Without it pheatmap would treat the distance matrix as data and compute distances between distances.

The Poisson distance is an alternative that models the count variance structure directly, and it takes the raw matrix, samples as rows (Witten 2011).

poisd <- PoissonDistance(t(counts(dds)))
m     <- as.matrix(poisd$dd)
rownames(m) <- paste(dds$dex, dds$cell, sep = " - ")
colnames(m) <- NULL
pheatmap(m,
         clustering_distance_rows = poisd$dd,
         clustering_distance_cols = poisd$dd,
         col  = colorRampPalette(rev(brewer.pal(9, "Blues")))(255),
         main = "Poisson distance on raw counts")

PCA

pcaData    <- plotPCA(vsd, intgroup = c("dex", "cell"), returnData = TRUE)
percentVar <- round(100 * attr(pcaData, "percentVar"))

ggplot(pcaData, aes(PC1, PC2, colour = dex, shape = cell)) +
  geom_point(size = 3.5, alpha = 0.9) +
  scale_colour_manual(values = pal_dex) +
  coord_fixed() +
  labs(
    x = paste0("PC1: ", percentVar[1], "% variance"),
    y = paste0("PC2: ", percentVar[2], "% variance"),
    title = "PCA, variance-stabilised counts"
  )

Read this plot carefully, because it justifies the design formula. Treatment separates the samples along PC1 (colour), while donor differences are comparable in magnitude and show up on PC2 (shape). Both sources are real and substantial, which is precisely why cell belongs in the model: the paired design pairs each treated sample with the untreated sample from the same donor, and testing without it would leave the donor variance in the residual.

The axis percentages do not sum to 100 because the remaining dimensions hold the rest of the variance.

Generalised PCA

GLM-PCA extends PCA to exponential-family likelihoods and operates on raw counts, sidestepping normalisation altogether (Townes et al. 2019).

gpca <- glmpca(counts(dds), L = 2)
gpca_dat <- gpca$factors
gpca_dat$dex  <- dds$dex
gpca_dat$cell <- dds$cell

ggplot(gpca_dat, aes(dim1, dim2, colour = dex, shape = cell)) +
  geom_point(size = 3.5, alpha = 0.9) +
  scale_colour_manual(values = pal_dex) +
  coord_fixed() +
  labs(title = "Generalised PCA on raw counts")

MDS

Useful when you have a distance matrix but not the underlying values.

mds_vst <- cbind(as.data.frame(colData(vsd)), cmdscale(sampleDistMatrix))
mds_poi <- cbind(as.data.frame(colData(dds)), cmdscale(as.matrix(poisd$dd)))

p1 <- ggplot(mds_vst, aes(`1`, `2`, colour = dex, shape = cell)) +
  geom_point(size = 3.5) + scale_colour_manual(values = pal_dex) +
  coord_fixed() + labs(title = "MDS, VST data", x = "dim 1", y = "dim 2")
p2 <- ggplot(mds_poi, aes(`1`, `2`, colour = dex, shape = cell)) +
  geom_point(size = 3.5) + scale_colour_manual(values = pal_dex) +
  coord_fixed() + labs(title = "MDS, Poisson distance", x = "dim 1", y = "dim 2")

print(p1); print(p2)


Differential expression

Running the pipeline

One call does size-factor estimation, gene-wise dispersion estimation, dispersion shrinkage toward a fitted trend, and the generalised linear model fit with Wald tests (Love, Huber, and Anders 2014).

dds <- DESeq(dds)

Always look at the dispersion fit. Gene-wise estimates (black) should scatter around the trend (red), with final shrunken values (blue) pulled toward it; high-dispersion outliers (circled) are flagged rather than shrunk. A fit that does not look like this is a sign something is wrong with the design or the data.

plotDispEsts(dds, main = "Dispersion estimates")

The results table

With dex last in the design, results() returns the trt vs untrt contrast by default. Being explicit costs nothing and documents intent.

res <- results(dds, contrast = c("dex", "trt", "untrt"), alpha = params$fdr)
mcols(res, use.names = TRUE)[, c("type", "description")]
#> DataFrame with 6 rows and 2 columns
#>                        type            description
#>                 <character>            <character>
#> baseMean       intermediate mean of normalized c..
#> log2FoldChange      results log2 fold change (ML..
#> lfcSE               results standard error: dex ..
#> stat                results Wald statistic: dex ..
#> pvalue              results Wald test p-value: d..
#> padj                results   BH adjusted p-values
summary(res)
#> 
#> out of 16637 with nonzero total read count
#> adjusted p-value < 0.05
#> LFC > 0 (up)       : 1993, 12%
#> LFC < 0 (down)     : 1609, 9.7%
#> outliers [1]       : 0, 0%
#> low counts [2]     : 323, 1.9%
#> (mean count < 10)
#> [1] see 'cooksCutoff' argument of ?results
#> [2] see 'independentFiltering' argument of ?results

What the columns mean. baseMean is the average of the normalised counts across all samples. log2FoldChange is the effect size, on a log base-2 scale: a value of 1.5 means expression is multiplied by 21.5≈2.832^{1.5} \approx 2.83. lfcSE is its standard error. pvalue comes from a Wald test of the null that the true log fold change is zero, and padj is that p-value adjusted for multiple testing.

Plenty of genes respond, which is biologically expected: airway smooth muscle is a known glucocorticoid target.

Multiple testing, concretely

n_tested <- sum(!is.na(res$pvalue))
n_raw    <- sum(res$pvalue < 0.05, na.rm = TRUE)
expected <- 0.05 * n_tested

cat(sprintf(
  "genes tested                     : %d\np < 0.05 (unadjusted)            : %d\nexpected under a global null     : %.0f\nimplied false-discovery fraction : %.0f%%\n",
  n_tested, n_raw, expected, 100 * expected / n_raw))
#> genes tested                     : 16637
#> p < 0.05 (unadjusted)            : 5069
#> expected under a global null     : 832
#> implied false-discovery fraction : 16%

cat(sprintf("\npadj < %.2f                       : %d\n",
            params$fdr, sum(res$padj < params$fdr, na.rm = TRUE)))
#> 
#> padj < 0.05                       : 3602

That last figure is the point of the exercise. Thresholding raw p-values at 0.05 would leave a list whose false-positive fraction is unacceptable, so DESeq2 reports Benjamini–Hochberg adjusted values instead (Benjamini and Hochberg 1995), which bound the expected proportion of false discoveries among the genes called significant.

Two ways to be stricter, and they are not equivalent. Lowering the FDR asks for more confidence that the effect is non-zero. Raising the log-fold-change threshold asks for a larger effect, and is tested properly rather than by filtering the table afterwards.

res_lfc1 <- results(dds, lfcThreshold = 1, alpha = params$fdr)
cat(sprintf("|LFC| > 1 and padj < %.2f: %d genes\n",
            params$fdr, sum(res_lfc1$padj < params$fdr, na.rm = TRUE)))
#> |LFC| > 1 and padj < 0.05: 214 genes

Pass alpha to results() whenever you depart from 0.1, so the independent filtering step (§7.1) is optimised for the threshold you actually use.

NA in padj is informative, not a defect: all counts were zero, the gene held a count outlier, or it was removed by independent filtering.

Other contrasts

resultsNames(dds)
#> [1] "Intercept"               "cell_N061011_vs_N052611" "cell_N080611_vs_N052611"
#> [4] "cell_N61311_vs_N052611"  "dex_trt_vs_untrt"
res_cell <- results(dds, contrast = c("cell", "N061011", "N61311"))
head(res_cell[order(res_cell$pvalue), c("baseMean", "log2FoldChange", "padj")], 3)
#> log2 fold change (MLE): cell N061011 vs N61311 
#>  
#> DataFrame with 3 rows and 3 columns
#>                     baseMean log2FoldChange        padj
#>                    <numeric>      <numeric>   <numeric>
#> ENSG00000106565.17   849.391       -3.56737 3.00230e-80
#> ENSG00000002933.8    542.946       -3.98045 1.99626e-61
#> ENSG00000188933.15   713.983        3.72212 1.35364e-59

contrast takes the variable, the numerator level, then the denominator. For interaction terms use name instead, drawn from resultsNames().

Strongest responses

resSig <- subset(res, padj < params$fdr)
cat("--- strongest down-regulation ---\n")
#> --- strongest down-regulation ---
head(as.data.frame(resSig[order(resSig$log2FoldChange), 
                          c("baseMean", "log2FoldChange", "padj")]), 5)
#>                   baseMean log2FoldChange         padj
#> ENSG00000216490.3 42.34575      -5.727085 9.323759e-04
#> ENSG00000267339.5 30.59027      -5.396920 2.815880e-11
#> ENSG00000146006.7 61.65554      -4.482586 1.003248e-10
#> ENSG00000155897.9 23.98920      -3.876977 2.302344e-05
#> ENSG00000213240.8 12.10015      -3.791532 1.162814e-02
cat("--- strongest up-regulation ---\n")
#> --- strongest up-regulation ---
head(as.data.frame(resSig[order(resSig$log2FoldChange, decreasing = TRUE),
                          c("baseMean", "log2FoldChange", "padj")]), 5)
#>                     baseMean log2FoldChange         padj
#> ENSG00000254692.1   62.15165      10.203271 1.469718e-02
#> ENSG00000179593.15  66.96657       9.501052 4.314279e-17
#> ENSG00000224712.12  35.55161       7.164664 6.304962e-03
#> ENSG00000109906.13 437.50246       6.372521 1.200079e-90
#> ENSG00000257663.1   24.36151       6.340942 1.449434e-02

Visualising the result

A single gene

topGene <- rownames(res)[which.min(res$padj)]

geneCounts <- plotCounts(dds, gene = topGene,
                         intgroup = c("dex", "cell"), returnData = TRUE)

p1 <- ggplot(geneCounts, aes(dex, count, colour = cell)) +
  geom_beeswarm(cex = 3, size = 3) +
  scale_y_log10() +
  scale_colour_manual(values = pal_cell) +
  labs(title = topGene, subtitle = "normalised counts", x = NULL)

p2 <- ggplot(geneCounts, aes(dex, count, colour = cell, group = cell)) +
  geom_point(size = 3) + geom_line(linewidth = 0.6) +
  scale_y_log10() +
  scale_colour_manual(values = pal_cell) +
  labs(title = topGene, subtitle = "paired within donor", x = NULL)

print(p1); print(p2)

The second panel is the honest picture of what the test actually evaluates: the model accounts for the donor effect, so it is the consistency of the within-donor change that carries the evidence, not the raw separation of the two groups.

MA-plot, with and without shrinkage

Before plotting effect sizes, shrink them. The apeglm estimator pulls noisy log fold changes from low-count genes toward zero while leaving genuinely large, well-supported effects nearly untouched (Zhu, Ibrahim, and Love 2018).

resShrunk <- lfcShrink(dds, coef = "dex_trt_vs_untrt", type = "apeglm")
resNoShr  <- results(dds, name = "dex_trt_vs_untrt")

op <- par(mfrow = c(1, 2))
plotMA(resShrunk, ylim = c(-5, 5), main = "apeglm-shrunken LFC")
plotMA(resNoShr,  ylim = c(-5, 5), main = "unshrunken LFC")

par(op)

Compare the left edge of the two panels. Without shrinkage, weakly expressed genes throw up large fold changes that are almost entirely noise; shrinkage narrows that spread without touching the strong signal on the right.

plotMA(resShrunk, ylim = c(-5, 5), main = "Top gene highlighted")
with(resShrunk[topGene, ], {
  points(baseMean, log2FoldChange, col = "#DD8452", cex = 2, lwd = 2)
  text(baseMean, log2FoldChange, topGene, pos = 2, col = "#DD8452")
})

The p-value histogram

A diagnostic worth running every time: a flat distribution with a spike near zero is what a healthy experiment looks like. Hills in the middle or at one suggest a problem with the model or unmodelled structure. Exclude very low counts first, as they generate artefactual spikes.

hist(res$pvalue[res$baseMean > 1], breaks = 0:20 / 20,
     col = "grey70", border = "white",
     xlab = "p-value", main = "p-values, genes with mean count > 1")

Clustering the most variable genes

Cluster deviations from each gene’s mean rather than absolute expression, otherwise the plot just sorts genes by how highly expressed they are.

# rowVars lives in MatrixGenerics, which SummarizedExperiment already loads;
# genefilter::rowVars is now just a thin re-export of it.
topVarGenes <- head(order(MatrixGenerics::rowVars(assay(vsd)),
                          decreasing = TRUE), 20)

mat <- assay(vsd)[topVarGenes, ]
mat <- mat - rowMeans(mat)
anno <- as.data.frame(colData(vsd)[, c("cell", "dex")])

pheatmap(mat, annotation_col = anno,
         annotation_colors = list(dex = pal_dex,
                                  cell = setNames(pal_cell, levels(vsd$cell))),
         col = colorRampPalette(rev(brewer.pal(9, "RdBu")))(255),
         main = "Top 20 variable genes, centred VST values")

Two patterns usually stand out: a block of genes separating one donor from the rest, and a block tracking dexamethasone.


Filtering and weighting

Independent filtering

Weakly expressed genes have essentially no power: Poisson noise at low counts swamps any biological effect. Binning by mean count makes this quantitative.

qs   <- c(0, quantile(res_lfc1$baseMean[res_lfc1$baseMean > 0], 0:6 / 6))
bins <- cut(res_lfc1$baseMean, qs)
levels(bins) <- paste0("~", round(signif((qs[-1] + qs[-length(qs)]) / 2, 2)))
fracSig <- tapply(res_lfc1$pvalue, bins, function(p) mean(p < 0.05, na.rm = TRUE))

barplot(fracSig, col = "#4C72B0", border = NA, las = 2,
        xlab = "mean normalised count", ylab = "fraction of small p-values",
        main = "Power by expression level")

Removing those genes is not simply tidying up. They contribute to the multiple-testing burden, so dropping them before the BH procedure lets more of the remaining genes clear the threshold: strictly more power, for free. DESeq2 does this automatically, choosing the threshold that maximises the number of genes below alpha.

The word independent is the load-bearing one. Filtering is legitimate only because the filter statistic (mean normalised count) is independent of the test statistic under the null (Bourgon, Gentleman, and Huber 2010). Filter on something correlated with the p-value and the procedure is invalid.

Independent hypothesis weighting

A generalisation: rather than a hard cutoff, weight hypotheses to optimise power (Ignatiadis et al. 2016).

library(IHW)
res_ihw <- results(dds, filterFun = ihw)

Annotation and export

Ensembl identifiers are precise but unreadable. Map them to symbols and Entrez identifiers, stripping the version suffix first since the annotation database keys on the unversioned identifier.

ens <- sub("\\..*$", "", rownames(res))   # ENSG00000000003.14 -> ENSG00000000003

res$symbol <- mapIds(org.Hs.eg.db, keys = ens, column = "SYMBOL",
                     keytype = "ENSEMBL", multiVals = "first")
res$entrez <- mapIds(org.Hs.eg.db, keys = ens, column = "ENTREZID",
                     keytype = "ENSEMBL", multiVals = "first")

resOrdered <- res[order(res$pvalue), ]
head(as.data.frame(resOrdered[, c("symbol", "baseMean", "log2FoldChange", "padj")]), 10)
#>                      symbol   baseMean log2FoldChange          padj
#> ENSG00000189221.9      MAOA  2371.2654       3.394261 4.038010e-134
#> ENSG00000120129.5     DUSP1  3417.2550       2.969904 2.807854e-129
#> ENSG00000101347.9    SAMHD1 14106.7200       3.749340 9.075598e-124
#> ENSG00000152583.12  SPARCL1   973.4792       4.500224 9.223326e-112
#> ENSG00000196136.17 SERPINA3  2708.3090       3.243291 4.022568e-109
#> ENSG00000211445.11     GPX3 12502.8860       3.768037 6.866804e-108
#> ENSG00000157214.13   STEAP2  3029.8509       2.011809  1.247268e-98
#> ENSG00000162614.18     NEXN  5507.3967       2.007382  3.468129e-96
#> ENSG00000109906.13   ZBTB16   437.5025       6.372521  1.200079e-90
#> ENSG00000125148.6      MT2A  3688.2942       2.232281  1.918550e-88

multiVals = "first" takes one mapping where several exist. That is a pragmatic choice, not a correct one; use multiVals = "list" if ambiguity matters for your downstream interpretation.

out_dir <- if (nzchar(Sys.getenv("RNASEQ_RESULTS_DIR"))) {
  Sys.getenv("RNASEQ_RESULTS_DIR")
} else {
  file.path(tempdir(), "results")   # a package build must not write outside it
}
dir.create(out_dir, showWarnings = FALSE, recursive = TRUE)
write.csv(as.data.frame(resOrdered), file.path(out_dir, "de_dex_trt_vs_untrt.csv"))
saveRDS(dds, file.path(out_dir, "dds.rds"))
cat("written to", out_dir, ":", list.files(out_dir), sep = "\n  ")
#> written to
#>   /tmp/RtmpqJL5r9/results
#>   :
#>   dds.rds
#>   de_dex_trt_vs_untrt.csv

Writing out dds.rds as well as the table means the fitted object can be reloaded for new contrasts without refitting.

Fold changes in genomic space

Because tximeta attached genomic coordinates, results can be requested as a GRanges and plotted along the chromosome directly.

has_gviz <- requireNamespace("Gviz", quietly = TRUE)

if (has_gviz && !is.null(rowRanges(dds)) && length(seqlevels(dds)) > 0) {
  library(Gviz)

  resGR <- lfcShrink(dds, coef = "dex_trt_vs_untrt",
                     type = "apeglm", format = "GRanges")
  resGR$symbol <- mapIds(org.Hs.eg.db, sub("\\..*$", "", names(resGR)),
                         "SYMBOL", "ENSEMBL")

  window <- resGR[topGene] + 1e6     # 1 Mb either side of the top gene
  strand(window) <- "*"
  sub_gr <- resGR[resGR %over% window]

  naOrDup <- is.na(sub_gr$symbol) | duplicated(sub_gr$symbol)
  sub_gr$group <- ifelse(naOrDup, names(sub_gr), sub_gr$symbol)
  status <- factor(ifelse(!is.na(sub_gr$padj) & sub_gr$padj < params$fdr,
                          "sig", "notsig"))

  options(ucscChromosomeNames = FALSE)
  plotTracks(
    list(
      GenomeAxisTrack(),
      DataTrack(sub_gr, data = "log2FoldChange", baseline = 0,
                type = "h", name = "log2 fold change", strand = "+"),
      AnnotationTrack(sub_gr, name = "gene ranges", feature = status)
    ),
    groupAnnotation = "group", notsig = "grey70", sig = "#DD8452"
  )
} else {
  message("Gviz not installed, or the object carries no ranges - skipping.")
}


Hidden batch effects

Suppose the donor identities had not been recorded. The donor effect would still be there, acting on many genes at once, and ignoring it would cost power and could bias the result. sva and RUVSeq recover such structure from the data itself (Leek 2014; Risso et al. 2014).

The honest test of these methods on this dataset is that we do know the donors, so we can check whether the recovered variables track them.

Surrogate variable analysis

library(sva)

dat <- counts(dds, normalized = TRUE)
dat <- dat[rowMeans(dat) > 1, ]

mod  <- model.matrix(~ dex, colData(dds))   # full model: treatment only
mod0 <- model.matrix(~ 1,   colData(dds))   # null model: intercept only
svseq <- svaseq(dat, mod, mod0, n.sv = 2)
#> Number of significant surrogate variables is:  2 
#> Iteration (out of 5 ):1  2  3  4  5

op <- par(mfrow = c(2, 1), mar = c(3, 5, 3, 1))
for (i in 1:2) {
  stripchart(svseq$sv[, i] ~ dds$cell, vertical = TRUE,
             main = paste0("SV", i), pch = 19, col = pal_cell)
  abline(h = 0, lty = 2)
}

par(op)

Note that cell is deliberately absent from both model matrices: we are pretending not to know it. The surrogate variables nonetheless separate the donors, which is the method working as intended.

ddssva <- dds
ddssva$SV1 <- svseq$sv[, 1]
ddssva$SV2 <- svseq$sv[, 2]
design(ddssva) <- ~ SV1 + SV2 + dex
# ddssva <- DESeq(ddssva); results(ddssva)
design(ddssva)
#> ~SV1 + SV2 + dex

Remove unwanted variation

RUVg needs empirical control genes: those with no evidence of an effect in a first pass that ignores the batch.

library(RUVSeq)

set <- newSeqExpressionSet(counts(dds))
set <- set[rowSums(counts(set) > 5) >= 2, ]
set <- betweenLaneNormalization(set, which = "upper")

not_sig   <- rownames(res)[which(res$pvalue > 0.1)]
empirical <- rownames(set)[rownames(set) %in% not_sig]
set <- RUVg(set, empirical, k = 2)

op <- par(mfrow = c(2, 1), mar = c(3, 5, 3, 1))
for (i in 1:2) {
  stripchart(pData(set)[, i] ~ dds$cell, vertical = TRUE,
             main = paste0("W", i), pch = 19, col = pal_cell)
  abline(h = 0, lty = 2)
}

par(op)
ddsruv <- dds
ddsruv$W1 <- set$W_1
ddsruv$W2 <- set$W_2
design(ddsruv) <- ~ W1 + W2 + dex
design(ddsruv)
#> ~W1 + W2 + dex

Either way, re-run DESeq() on the new design to re-estimate everything.


Time course designs

A different question needs a different test. For a time course, the genes of interest are usually those whose response differs between conditions over time, which is an interaction, not a main effect. The fission data is a yeast oxidative-stress time course with and without a deletion of atf21 (Leong et al. 2014).

library(fission)
data("fission")

ddsTC <- DESeqDataSet(fission, ~ strain + minute + strain:minute)
ddsTC <- DESeq(ddsTC, test = "LRT", reduced = ~ strain + minute)
resTC <- results(ddsTC)
resTC$symbol <- mcols(ddsTC)$symbol

head(as.data.frame(resTC[order(resTC$padj), c("symbol", "baseMean", "padj")]), 4)
#>              symbol baseMean         padj
#> SPBC2F12.09c  atf21 174.6712 1.334526e-15
#> SPAC1002.18    urg3 444.5050 1.747308e-07
#> SPAC1002.19    urg1 336.3732 6.489157e-05
#> SPAC1002.17c   urg2 261.7731 3.466817e-04

The likelihood-ratio test drops the strain:minute term, so a small p-value means the strains diverged at one or more time points after time zero. A gene that moved identically over time in both strains gets a large p-value, which is the correct behaviour: it is not a strain-specific response.

fiss <- plotCounts(ddsTC, which.min(resTC$padj),
                   intgroup = c("minute", "strain"), returnData = TRUE)
fiss$minute <- as.numeric(as.character(fiss$minute))

ggplot(fiss, aes(minute, count, colour = strain, group = strain)) +
  geom_point(size = 2.5) +
  stat_summary(fun = mean, geom = "line", linewidth = 0.8) +   # not fun.y
  scale_y_log10() +
  scale_colour_manual(values = unname(pal_dex)) +
  labs(title = "Condition-specific time profile",
       x = "minutes after stress", y = "normalised count")

Individual time points can still be tested with Wald tests:

res30 <- results(ddsTC, name = "strainmut.minute30", test = "Wald")
res30[which.min(res30$padj), c("log2FoldChange", "pvalue", "padj")]
#> log2 fold change (MLE): strainmut.minute30 
#> Wald test p-value: strainmut.minute30 
#> DataFrame with 1 row and 3 columns
#>              log2FoldChange      pvalue      padj
#>                   <numeric>   <numeric> <numeric>
#> SPBC2F12.09c       -2.60047 4.14099e-05  0.279931

And the coefficients clustered to see the shapes of the responses:

betas <- coef(ddsTC)
topGenesTC <- head(order(resTC$padj), 20)
mat <- betas[topGenesTC, -c(1, 2)]        # drop intercept and strain main effect
thr <- 3
mat[mat < -thr] <- -thr
mat[mat >  thr] <-  thr

pheatmap(mat, breaks = seq(-thr, thr, length.out = 101),
         col = colorRampPalette(rev(brewer.pal(9, "RdBu")))(100),
         cluster_cols = FALSE,
         main = "Log2 fold changes, 20 most significant genes")

These are maximum-likelihood estimates. For shrunken values use lfcShrink(), one coefficient at a time.


Adapting this to your own data

Four things to change, and nothing else:

  1. workflow/config.yaml — your run accessions or local FASTQ paths, and the reference release for your organism. Keep GENCODE if you want tximeta to resolve annotation automatically; otherwise pass skipMeta = TRUE and supply a tx2gene table yourself.
  2. data/coldata.csv — one row per sample. names and files are required; every other column becomes available to the design formula.
  3. The design formula — ~ cell + dex encodes “test treatment, controlling for donor”. Replace cell with whatever your nuisance structure is (batch, run, litter, plot, block), and if you want to ask whether an effect differs between groups, add an interaction: ~ group + treatment + group:treatment.
  4. params$fdr and params$lfc_threshold in the YAML header.

Then knit with your own source:

rmarkdown::render(
  "analysis/rnaseq-gene-pipeline.Rmd",
  params = list(source = "quants", coldata = "../data/coldata.csv", fdr = 0.05)
)

A fifth thing, which is not in this repository and cannot be: the bench decisions in the bench section. Enrichment chemistry, strandedness and depth are fixed long before any code runs, and the pipeline has to be told what was done – -l A infers strandedness from the data, but it can only infer what the library actually is.

Two cautions worth repeating. Never feed in counts that have already been normalised for library size; the model needs raw counts and handles depth itself. And set the reference level of your factor of interest explicitly with relevel() rather than relying on alphabetical order, or the sign of every fold change may be the opposite of what you intend.


Session information

Recording this is not a formality. It is what lets you work out, a year from now, why a script that used to run no longer does.

sessionInfo()
#> R version 4.4.2 (2024-10-31)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.1 LTS
#> 
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so;  LAPACK version 3.12.0
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8       
#>  [4] LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C              
#> [10] LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> time zone: Etc/UTC
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] grid      stats4    stats     graphics  grDevices utils     datasets  methods  
#> [9] base     
#> 
#> other attached packages:
#>  [1] fission_1.26.0              RUVSeq_1.40.0               edgeR_4.4.2                
#>  [4] limma_3.62.2                EDASeq_2.40.0               ShortRead_1.64.0           
#>  [7] GenomicAlignments_1.42.0    Rsamtools_2.22.0            Biostrings_2.74.1          
#> [10] XVector_0.46.0              sva_3.54.0                  BiocParallel_1.40.2        
#> [13] genefilter_1.88.0           mgcv_1.9-1                  nlme_3.1-166               
#> [16] Gviz_1.50.0                 GenomicFeatures_1.58.0      airway_1.26.0              
#> [19] org.Hs.eg.db_3.20.0         AnnotationDbi_1.68.0        apeglm_1.28.0              
#> [22] ggbeeswarm_0.7.3            RColorBrewer_1.1-3          pheatmap_1.0.13            
#> [25] ggplot2_4.0.4               glmpca_0.2.0                PoiClaClu_1.0.2.1          
#> [28] vsn_3.74.0                  DESeq2_1.46.0               tximeta_1.24.0             
#> [31] SummarizedExperiment_1.36.0 Biobase_2.66.0              GenomicRanges_1.58.0       
#> [34] GenomeInfoDb_1.42.3         IRanges_2.40.1              S4Vectors_0.44.0           
#> [37] BiocGenerics_0.52.0         MatrixGenerics_1.18.1       matrixStats_1.5.0          
#> 
#> loaded via a namespace (and not attached):
#>   [1] splines_4.4.2            BiocIO_1.16.0            bitops_1.1-0            
#>   [4] filelock_1.0.3           R.oo_1.27.1              tibble_3.2.1            
#>   [7] preprocessCore_1.68.0    XML_3.99-0.25            rpart_4.1.23            
#>  [10] lifecycle_1.0.5          httr2_1.0.7              pwalign_1.2.0           
#>  [13] lattice_0.22-6           ensembldb_2.30.0         MASS_7.3-61             
#>  [16] backports_1.5.1          magrittr_2.0.3           Hmisc_5.3-1             
#>  [19] sass_0.4.9               rmarkdown_2.29           jquerylib_0.1.4         
#>  [22] yaml_2.3.10              otel_0.3.0               DBI_1.4.0               
#>  [25] abind_1.4-8              zlibbioc_1.52.0          R.utils_2.13.0          
#>  [28] purrr_1.0.2              AnnotationFilter_1.30.0  biovizBase_1.54.0       
#>  [31] RCurl_1.98-1.20          nnet_7.3-19              VariantAnnotation_1.52.0
#>  [34] rappdirs_0.3.3           GenomeInfoDbData_1.2.13  annotate_1.84.0         
#>  [37] pkgdown_2.2.1            codetools_0.2-20         DelayedArray_0.32.0     
#>  [40] xml2_1.3.6               tidyselect_1.2.1         UCSC.utils_1.2.0        
#>  [43] farver_2.1.2             BiocFileCache_2.14.0     base64enc_0.1-3         
#>  [46] jsonlite_1.8.9           Formula_1.2-6            survival_3.8-3          
#>  [49] systemfonts_1.1.0        bbmle_1.0.26             tools_4.4.2             
#>  [52] progress_1.2.3           ragg_1.5.2               Rcpp_1.1.2              
#>  [55] glue_1.8.0               gridExtra_2.3.1          SparseArray_1.6.2       
#>  [58] xfun_0.49                dplyr_1.2.1              withr_3.0.2             
#>  [61] numDeriv_2016.8-1.1      BiocManager_1.30.25      fastmap_1.2.0           
#>  [64] latticeExtra_0.6-31      digest_0.6.37            R6_2.5.1                
#>  [67] textshaping_0.4.1        colorspace_2.1-4         jpeg_0.1-11             
#>  [70] dichromat_2.0-1          biomaRt_2.62.1           RSQLite_3.54.1          
#>  [73] R.methodsS3_1.8.2        generics_0.1.4           hexbin_1.28.6           
#>  [76] data.table_1.18.6.1      rtracklayer_1.66.0       prettyunits_1.2.0       
#>  [79] httr_1.4.9               htmlwidgets_1.6.4        S4Arrays_1.6.0          
#>  [82] pkgconfig_2.0.3          gtable_0.3.6             blob_1.3.0              
#>  [85] hwriter_1.3.2.1          S7_1.0.0                 htmltools_0.5.8.1       
#>  [88] ProtGenerics_1.38.0      scales_1.4.0             png_0.1-9               
#>  [91] rstudioapi_0.17.1        knitr_1.49               rjson_0.2.23            
#>  [94] checkmate_2.3.4          coda_0.19-4.1            curl_6.0.1              
#>  [97] bdsmatrix_1.3-7          cachem_1.1.0             stringr_1.5.1           
#> [100] BiocVersion_3.20.0       parallel_4.4.2           vipor_0.4.7             
#> [103] foreign_0.8-87           restfulr_0.0.17          desc_1.4.3              
#> [106] pillar_1.10.0            vctrs_0.7.3              dbplyr_2.6.0            
#> [109] xtable_1.8-4             cluster_2.1.8            htmlTable_2.5.0         
#> [112] beeswarm_0.4.0           tximport_1.34.0          evaluate_1.0.1          
#> [115] mvtnorm_1.5-0            cli_3.6.3                locfit_1.5-9.12         
#> [118] compiler_4.4.2           rlang_1.3.0              crayon_1.5.3            
#> [121] labeling_0.4.3           aroma.light_3.36.0       interp_1.1-6            
#> [124] emdbook_1.3.14           affy_1.84.0              plyr_1.8.9              
#> [127] fs_1.6.5                 stringi_1.8.4            deldir_2.0-4            
#> [130] viridisLite_0.4.3        txdbmaker_1.2.1          lazyeval_0.2.3          
#> [133] Matrix_1.7-1             BSgenome_1.74.0          hms_1.1.4               
#> [136] bit64_4.8.6              KEGGREST_1.46.0          statmod_1.5.2           
#> [139] AnnotationHub_3.14.0     memoise_2.0.1            affyio_1.76.0           
#> [142] bslib_0.8.0              bit_4.6.0

References

Agilent Technologies. n.d. “Agilent Automated Electrophoresis Portfolio: Sample Quality Control in Next-Generation Sequencing Workflows. Application Compendium.” 5994-2142EN. Agilent Technologies. https://www.agilent.com/cs/library/applications/application_ngs-sample-qc-automated-electrophoresis-5994-2142en-agilent.pdf.
Benjamini, Yoav, and Yosef Hochberg. 1995. “Controlling the False Discovery Rate: A Practical and Powerful Approach to Multiple Testing.” Journal of the Royal Statistical Society, Series B 57 (1): 289–300. https://doi.org/10.1111/j.2517-6161.1995.tb02031.x.
Bourgon, Richard, Robert Gentleman, and Wolfgang Huber. 2010. “Independent Filtering Increases Detection Power for High-Throughput Experiments.” Proceedings of the National Academy of Sciences 107 (21): 9546–51. https://doi.org/10.1073/pnas.0914005107.
Cevher-Keskin, Birsen, Yasemin Yıldızhan, A. Hediye Sekmen, Rumeysa Fayetorbay, Osman Uğur Sezerman, Buğra Özer, Selma Onarıcı, İsmail Türkan, and Mahmut Tör. 2025. “Deciphering Drought-Response in Wheat (Triticum Aestivum): Physiological, Biochemical, and Transcriptomic Insights into Tolerant and Sensitive Cultivars Under Dehydration Shock.” Frontiers in Plant Science. https://doi.org/10.3389/fpls.2025.1649378.
Ewels, Philip A., Alexander Peltzer, Sven Fillinger, Harshil Patel, Johannes Alneberg, Andreas Wilm, Maxime Ulysse Garcia, Paolo Di Tommaso, and Sven Nahnsen. 2020. “The Nf-Core Framework for Community-Curated Bioinformatics Pipelines.” Nature Biotechnology 38 (3): 276–78. https://doi.org/10.1038/s41587-020-0439-x.
Himes, Blanca E., Xiaofeng Jiang, Peter Wagner, Ruoxi Hu, Qiyu Wang, Barbara Klanderman, Reid M. Whitaker, et al. 2014. “RNA-Seq Transcriptome Profiling Identifies CRISPLD2 as a Glucocorticoid Responsive Gene That Modulates Cytokine Function in Airway Smooth Muscle Cells.” PLoS ONE 9 (6): e99625. https://doi.org/10.1371/journal.pone.0099625.
Ignatiadis, Nikolaos, Bernd Klaus, Judith B. Zaugg, and Wolfgang Huber. 2016. “Data-Driven Hypothesis Weighting Increases Detection Power in Genome-Scale Multiple Testing.” Nature Methods 13 (7): 577–80. https://doi.org/10.1038/nmeth.3885.
Illumina, Inc. 2025. “Methods for RNA Sequencing.” Method Guide M-GL-00034 v2.0. Illumina, Inc. https://emea.illumina.com/content/dam/illumina-marketing/emea/PDF_Files/rna-seq-workflows-guide-m-gl-00034-20250904-final-feedback.pdf.
Leek, Jeffrey T. 2014. “svaseq: Removing Batch Effects and Other Unwanted Noise from Sequencing Data.” Nucleic Acids Research 42 (21): e161. https://doi.org/10.1093/nar/gku864.
Leong, Hui Sun, Keren Dawson, Chris Wirth, Yaoyong Li, Yvonne Connolly, Duncan L. Smith, Caroline R. Wilkinson, and Crispin J. Miller. 2014. “A Global Non-Coding RNA System Modulates Fission Yeast Protein Levels in Response to Stress.” Nature Communications 5: 3947. https://doi.org/10.1038/ncomms4947.
Love, Michael I., John B. Hogenesch, and Rafael A. Irizarry. 2016. “Modeling of RNA-seq Fragment Sequence Bias Reduces Systematic Errors in Transcript Abundance Estimation.” Nature Biotechnology 34 (12): 1287–91. https://doi.org/10.1038/nbt.3682.
Love, Michael I., Wolfgang Huber, and Simon Anders. 2014. “Moderated Estimation of Fold Change and Dispersion for RNA-seq Data with DESeq2.” Genome Biology 15 (12): 550. https://doi.org/10.1186/s13059-014-0550-8.
New England Biolabs. 2023. “Directional Poly(a) mRNA Enrichment: Obtain Superior NGS Library Performance with Lower Input Amounts Using the NEBNext Ultra II Directional RNA Library Prep Kit for Illumina.” Technical Note NEB #E7760. New England Biolabs. https://www.neb.com/en/-/media/nebus/files/application-notes/technote_nebnext_ultra_ii_directional_rrna_depletion.pdf.
nf-core community. 2026. “nf-core/rnaseq: Output Documentation.” https://nf-co.re/rnaseq/output.
Patro, Rob, Geet Duggal, Michael I. Love, Rafael A. Irizarry, and Carl Kingsford. 2017. “Salmon Provides Fast and Bias-Aware Quantification of Transcript Expression.” Nature Methods 14 (4): 417–19. https://doi.org/10.1038/nmeth.4197.
Risso, Davide, John Ngai, Terence P. Speed, and Sandrine Dudoit. 2014. “Normalization of RNA-seq Data Using Factor Analysis of Control Genes or Samples.” Nature Biotechnology 32 (9): 896–902. https://doi.org/10.1038/nbt.2931.
Robert, Christelle, and Mick Watson. 2015. “Errors in RNA-Seq Quantification Affect Genes of Relevance to Human Disease.” Genome Biology 16: 177. https://doi.org/10.1186/s13059-015-0734-x.
Sainz, María Martha, Mariana Sotelo-Silveira, Carla V. Filippi, and Sofía Zardo. 2024. “Legume-Rhizobia Symbiosis: Translatome Analysis.” Genetics and Molecular Biology. https://doi.org/10.1590/1678-4685-GMB-2023-0284.
Soneson, Charlotte, Michael I. Love, and Mark D. Robinson. 2015. “Differential Analyses for RNA-seq: Transcript-Level Estimates Improve Gene-Level Inferences.” F1000Research 4: 1521. https://doi.org/10.12688/f1000research.7563.1.
Srivastava, Avi, Laraib Malik, Hirak Sarkar, Mohsen Zakeri, Fatemeh Almodaresi, Charlotte Soneson, Michael I. Love, Carl Kingsford, and Rob Patro. 2020. “Alignment and Mapping Methodology Influence Transcript Abundance Estimation.” Genome Biology 21 (1): 239. https://doi.org/10.1186/s13059-020-02151-8.
Thermo Fisher Scientific. 2012. “PureLink RNA Mini Kit: For Purification of Total RNA from a Large Variety of Samples. User Guide.” MAN0000406, Rev. 14. Thermo Fisher Scientific. https://www.thermofisher.com/TFS-Assets/LSG/manuals/purelink_rna_mini_kit_man.pdf.
Townes, F. William, Stephanie C. Hicks, Martin J. Aryee, and Rafael A. Irizarry. 2019. “Feature Selection and Dimension Reduction for Single-Cell RNA-Seq Based on a Multinomial Model.” Genome Biology 20 (1): 295. https://doi.org/10.1186/s13059-019-1861-6.
Trapnell, Cole, David G. Hendrickson, Martin Sauvageau, Loyal Goff, John L. Rinn, and Lior Pachter. 2013. “Differential Analysis of Gene Regulation at Transcript Resolution with RNA-seq.” Nature Biotechnology 31 (1): 46–53. https://doi.org/10.1038/nbt.2450.
Witten, Daniela M. 2011. “Classification and Clustering of Sequencing Data Using a Poisson Model.” The Annals of Applied Statistics 5 (4): 2493–2518. https://doi.org/10.1214/11-AOAS493.
Zhu, Anqi, Joseph G. Ibrahim, and Michael I. Love. 2018. “Heavy-Tailed Prior Distributions for Sequence Count Data: Removing the Noise and Preserving Large Differences.” Bioinformatics 35 (12): 2084–92. https://doi.org/10.1093/bioinformatics/bty895.