Bulk RNA-seq Analysis in R, Start to Finish
By the end of this guide you will have a reproducible R script that turns a directory of salmon quantification folders into three artifacts: a variance-stabilized expression matrix for exploratory work, a differential expression table with shrunken log fold changes, and a pathway enrichment table ranked by a signed test statistic. You need R 4.3 or newer and Bioconductor 3.18 or newer. You also need roughly 16 GB of RAM and paired-end FASTQ files with at least 20 million read pairs per sample. The examples assume human data aligned to GENCODE v45 on GRCh38. If your samples are your own longitudinal blood draws, read section 9 before you design the comparison, because the modeling choices differ from a standard two-group experiment.
1. Install the packages you will use
Install everything once and record the versions. Reproducibility failures in RNA-seq are usually version drift in annotation. The statistics are usually not the cause.
install.packages("BiocManager")
BiocManager::install(c(
"tximport", "GenomicFeatures", "DESeq2", "apeglm",
"vsn", "limma", "fgsea", "org.Hs.eg.db", "AnnotationDbi",
"PCAtools", "sva", "immunedeconv"
))
writeLines(capture.output(sessionInfo()), "sessionInfo.txt")
Pin the GENCODE release you used for quantification. A transcript-to-gene map from a different release will silently drop genes at the import step.
2. Quantify transcripts with salmon before you touch R
Alignment-free quantification with salmon is the approach we would use for a standard differential expression question. It runs in minutes per sample on a laptop-class CPU, and it corrects for fragment-level biases that shift fold change estimates. Build a decoy-aware index so that reads from unannotated genomic regions are not forced onto transcripts.
grep '^>' <(gunzip -c GRCh38.primary_assembly.genome.fa.gz) \
| cut -d ' ' -f 1 | sed 's/>//g' > decoys.txt
cat gencode.v45.transcripts.fa.gz GRCh38.primary_assembly.genome.fa.gz > gentrome.fa.gz
salmon index -t gentrome.fa.gz -d decoys.txt -p 12 -k 31 --gencode -i idx_v45
salmon quant -i idx_v45 -l A \
-1 S01_R1.fastq.gz -2 S01_R2.fastq.gz \
-p 12 --gcBias --seqBias --posBias \
--numBootstraps 30 -o quants/S01
-l A lets salmon infer strandedness, which you should then verify in quants/S01/lib_format_counts.json. A stranded library that reports IU means something went wrong upstream. The --gcBias flag matters when samples were prepared in different batches, since GC-dependent coverage is one of the more common batch artifacts. Keep the bootstraps: they give you per-sample technical variance if you later move to a transcript-level method. If you prefer a genome alignment instead, STAR plus featureCounts is a reasonable substitute and is the path most published workflows still take 1.
3. Build the transcript-to-gene map and import counts
tximport aggregates transcript abundances to gene level and produces the offset matrix that DESeq2 uses to correct for average transcript length across samples. Build the map from the same GTF that generated your index.
library(GenomicFeatures); library(tximport)
txdb <- makeTxDbFromGFF("gencode.v45.annotation.gtf.gz", format = "gtf")
k <- keys(txdb, keytype = "TXNAME")
tx2gene <- AnnotationDbi::select(txdb, k, "GENEID", "TXNAME")
samples <- read.csv("samples.csv", stringsAsFactors = FALSE)
files <- file.path("quants", samples$sample_id, "quant.sf")
names(files) <- samples$sample_id
stopifnot(all(file.exists(files)))
txi <- tximport(files, type = "salmon", tx2gene = tx2gene,
ignoreTxVersion = FALSE, countsFromAbundance = "no")
Check nrow(txi$counts) against the number of genes in the GTF. If you lost a third of them, your transcript IDs carry version suffixes that the map does not, and you should set ignoreTxVersion = TRUE. Leave countsFromAbundance = "no" for DESeq2, because DESeq2 wants raw counts plus the length offsets.
4. Assemble the DESeqDataSet and filter
The design formula is the most consequential line in the script. Put nuisance variables first and the variable of interest last, because DESeq2 reports results for the last term by default.
library(DESeq2)
rownames(samples) <- samples$sample_id
samples$condition <- factor(samples$condition, levels = c("baseline", "treated"))
samples$batch <- factor(samples$batch)
dds <- DESeqDataSetFromTximport(txi, colData = samples,
design = ~ batch + condition)
smallest <- min(table(samples$condition))
keep <- rowSums(counts(dds) >= 10) >= smallest
dds <- dds[keep, ]
That filter typically takes a human dataset from about 62,000 annotated genes to 14,000 to 18,000 expressed ones. Filtering on a count threshold rather than on counts per million keeps the rule interpretable across libraries of different depth. Independent filtering inside results() will remove a few more low-information genes later, which raises power at a fixed false discovery rate. Benchmarks across count-based methods consistently show that pre-filtering improves error rate control for the negative binomial models 2.
5. Run quality control before any statistics
Transform the counts for visualization. The variance stabilizing transform is fast and behaves well above roughly 30 samples, while rlog is better for small designs with widely varying library sizes.
vsd <- vst(dds, blind = TRUE)
plotPCA(vsd, intgroup = c("condition", "batch"))
sampleDists <- dist(t(assay(vsd)))
pheatmap::pheatmap(as.matrix(sampleDists),
clustering_distance_rows = sampleDists)
Three diagnostics decide whether the dataset is usable. First, library size: anything below half the median depth will contribute little. Second, the fraction of reads assigned to a handful of genes. In whole blood collected without globin depletion, the hemoglobin transcripts HBB, HBA1 and HBA2 frequently take more than half of the mRNA. That flattens your effective depth for everything else.
cpm <- edgeR::cpm(counts(dds))
globin <- c("ENSG00000244734", "ENSG00000206172", "ENSG00000188536")
colSums(cpm[intersect(globin, rownames(cpm)), , drop = FALSE]) / 1e4 # percent
Third, sample identity. Check XIST and RPS4Y1 against recorded sex, and if you have whole-genome sequencing on the same person, confirm concordance directly by comparing genotypes called from the RNA reads against your VCF. Sample swaps are the most common unrecoverable error in a multi-timepoint study.
6. Handle batch effects in the model without touching the matrix
If batch is recorded and not confounded with your variable of interest, keep ~ batch + condition and let DESeq2 estimate the batch coefficients. Do not feed batch-corrected values back into the count model. For plotting only, remove the batch component from the transformed matrix.
library(limma)
mat <- assay(vsd)
mm <- model.matrix(~ condition, colData(vsd))
assay(vsd) <- removeBatchEffect(mat, batch = vsd$batch, design = mm)
When the batch structure is unknown, estimate surrogate variables with sva on the filtered counts and add them to the design. Reviews of differential expression practice treat unmodeled technical structure as a leading source of irreproducible gene lists 3. Check that your surrogate variables are not tracking the biological contrast before you include them.
7. Fit the model and extract results
dds <- DESeq(dds)
resultsNames(dds)
res <- results(dds, name = "condition_treated_vs_baseline", alpha = 0.05)
res <- lfcShrink(dds, coef = "condition_treated_vs_baseline",
res = res, type = "apeglm")
summary(res)
res_df <- as.data.frame(res)
res_df$symbol <- mapIds(org.Hs.eg.db, sub("\\..*", "", rownames(res_df)),
"SYMBOL", "ENSEMBL")
write.csv(res_df[order(res_df$padj), ], "de_results.csv")
Use the shrunken log fold changes for ranking and for any plot. The apeglm estimator pulls fold changes of low-count genes toward zero without shrinking well-measured large effects, so a gene with a 6-fold change and 4 counts stops outranking a gene with a 1.5-fold change and 4,000 counts. Report padj from the Benjamini-Hochberg procedure and state the threshold you used. A fold change cutoff applied after the fact is not a test. If you care about effect size, use results(dds, lfcThreshold = 0.585) and let the model test against that threshold.
Comparative work on count-based methods finds DESeq2 and edgeR to be broadly similar in ranking, with differences concentrated in low-count genes and in how each controls the false discovery rate under unequal group sizes 32. We use DESeq2 by default for its shrinkage behavior and its handling of length offsets from tximport.
8. Move from genes to pathways
Single gene results from one person’s blood are noisy. Pathway-level summaries aggregate across correlated genes and are more stable. Rank all genes by the Wald statistic and run a preranked enrichment test rather than a hypergeometric test on a thresholded list, since thresholding discards most of the signal.
library(fgsea)
ranks <- res_df$stat
names(ranks) <- res_df$symbol
ranks <- sort(ranks[!is.na(names(ranks)) & !is.na(ranks)], decreasing = TRUE)
pathways <- gmtPathways("h.all.v2023.2.Hs.symbols.gmt")
fg <- fgseaMultilevel(pathways, ranks, minSize = 15, maxSize = 500)
fg <- fg[order(fg$padj), ]
The Hallmark collection of 50 gene sets is the right starting point, because it has low redundancy and each set is large enough to give a stable enrichment score. Reactome and GO are useful follow-ups, and both carry heavy set overlap that inflates the apparent number of hits.
For whole blood, much of the observed differential expression is shifting cell composition rather than changed regulation within a cell type. Estimate the composition explicitly before you interpret anything.
library(immunedeconv)
tpm <- txi$abundance[rownames(dds), ]
frac <- deconvolute(tpm, "quantiseq")
Deconvolution methods take a reference signature matrix of cell-type profiles and solve for the mixture proportions in each bulk sample. Integrated pipelines for bulk tumor data treat this immune composition estimate as a first-class output alongside the differential expression table 4. Single-cell references improve those signatures substantially, and combined bulk plus single-cell designs are now a standard way to attribute a bulk signal to a cell population 56.
9. Design for repeated samples from one person
An n-of-1 longitudinal study is a different statistical object from a case-control study. You cannot run differential expression on a single sample against a single other sample, because there is no way to estimate dispersion. Plan at least four timepoints per state, and ideally more, so that within-person biological variability is estimable. Power calculations for bulk RNA-seq depend jointly on replicate count, sequencing depth and the dispersion you expect, and tools exist to compute this before you spend money on library prep 7.
For a time course, avoid pairwise comparisons against timepoint zero. Fit a smooth function of time and test whether it is needed.
library(splines)
design(dds) <- ~ ns(time_h, df = 3)
dds <- DESeq(dds, test = "LRT", reduced = ~ 1)
res_time <- results(dds)
Three degrees of freedom is a sensible default for six to ten timepoints. The likelihood ratio test asks whether any temporal pattern fits better than a flat line, which is usually the question you want. Methods built specifically for temporal count data handle autocorrelation and irregular sampling better than a spline term, and are worth the extra effort for dense series 8. If your timepoints span weeks, include season, time of day of the draw, and any acute illness as covariates, because all three move blood transcriptomes more than most interventions do.
Finally, keep the interpretation bounded. RNA expression from blood is a measurement of cell state at one moment, and it is not a clinical test. If a result looks medically significant to you, take the data to a physician who can order validated diagnostics 9.
Common problems
A mapping rate below 70% in quants/S01/logs/salmon_quant.log usually means adapter contamination, the wrong species index, or heavy rRNA carryover. Run fastqc and check overrepresented sequences before rebuilding anything.
If DESeqDataSetFromTximport errors on row name mismatch, your colData row names and the names of the files vector are in different orders. DESeq2 does not reorder for you.
If PCA separates samples by batch rather than by condition, and every sample in one condition came from one batch, the effect is not separable. No software fixes this. The experiment has to be rerun with samples randomized across batches.
If nearly every gene is significant, look for a single outlier sample driving the dispersion estimates. Check assays(dds)[["cooks"]] for maximum Cook’s distances, and inspect plotDispEsts(dds) for a fitted curve that does not track the point cloud.
If enrichment results change completely between gene set collections, your signal is weak. Report the Hallmark result and the ranking statistic, and treat the rest as exploratory. User-friendly wrapper packages exist for running these steps through a graphical interface, which is a reasonable way to sanity-check a script’s output against an independent implementation 10.
Footnotes
-
Amarinder Singh Thind, Isha Monga, Prasoon Kumar Thakur, et al. Demystifying emerging bulk RNA-Seq applications: the application and utility of bioinformatic methodology. Briefings in Bioinformatics, 2021. https://doi.org/10.1093/bib/bbab259 ↩
-
Matteo Calgaro, Chiara Romualdi, Levi Waldron, et al. Assessment of statistical methods from single cell, bulk RNA-seq, and metagenomics applied to microbiome data. Genome Biology, 2020. https://doi.org/10.1186/s13059-020-02104-1 ↩ ↩2
-
Maryam Kalantari-Dehaghi, Neda Ghohabi-Esfahani, Modjtaba Emadi-Baygi. From bulk RNA sequencing to spatial transcriptomics: a comparative review of differential gene expression analysis methods. Human Genomics, 2025. https://doi.org/10.1186/s40246-025-00884-w ↩ ↩2
-
Lin Yang, Jin Wang, Jennifer Altreuter, et al. Tutorial: integrative computational analysis of bulk RNA-sequencing data to characterize tumor immunity using RIMA. Nature Protocols, 2023. https://doi.org/10.1038/s41596-023-00841-8 ↩
-
Yongxing Chen, Wei Wu, Chenxin Jin, et al. Integrating Single-Cell RNA-Seq and Bulk RNA-Seq Data to Explore the Key Role of Fatty Acid Metabolism in Breast Cancer. International Journal of Molecular Sciences, 2023. https://doi.org/10.3390/ijms241713209 ↩
-
Yunjin Li, Lu Ma, Duojiao Wu, et al. Advances in bulk and single-cell multi-omics approaches for systems biology and precision medicine. Briefings in Bioinformatics, 2021. https://doi.org/10.1093/bib/bbab024 ↩
-
Hyeongseon Jeon, Juan Xie, Yeseul Jeon, et al. Statistical Power Analysis for Designing Bulk, Single-Cell, and Spatial Transcriptomics Experiments: Review, Tutorial, and Perspectives. Biomolecules, 2023. https://doi.org/10.3390/biom13020221 ↩
-
Vera-Khlara S. Oh, Robert W. Li. Temporal Dynamic Methods for Bulk RNA-Seq Time Series Data. Genes, 2021. https://doi.org/10.3390/genes12030352 ↩
-
Jorge A. Tzec‐Interián, Daianna González‐Padilla, Elsa B. Góngora‐Castillo. Bioinformatics perspectives on transcriptomics: A comprehensive review of bulk and single‐cell RNA sequencing analyses. Quantitative Biology, 2025. https://doi.org/10.1002/qub2.78 ↩
-
Daniel Dimitrov, Quan Gu. BingleSeq: a user-friendly R package for bulk and single-cell RNA-Seq data analysis. PeerJ, 2020. https://doi.org/10.7717/peerj.10469 ↩
Pothos builds longitudinal molecular profiles of individuals: whole-genome sequencing, single-cell RNA sequencing, and plasma proteomics, delivered as a detailed report, every data file, and stored cells. Build your profile.