Summary of DGE workflow

Author

You!

Published

October 28, 2026

Approximate time: 15 minutes

Learning Objectives

  • Identify the R commands needed to run a complete differential expression analysis using DESeq2

Libraries

library(tidyverse)
library(DESeq2)
library(ggrepel)
library(pheatmap)
library(annotables)
library(clusterProfiler)
library(DOSE)
library(pathview)
library(org.Hs.eg.db)
library(tximport)
library(RColorBrewer)

We have detailed the various steps in a differential expression analysis workflow, providing theory with example code. To provide a more succinct reference for the code needed to run a DGE analysis, we have summarized the steps in an analysis below:

Obtaining gene-level counts from your preprocessing and create DESeq object

If you have a traditional raw count matrix

Load data and metadata

data <- read_table("../Data/Vampirium_counts_traditional.tsv") 

meta <- read_csv("../Data/samplesheet.csv")

Check that the row names of the metadata equal the column names of the raw counts data

### Check that sample names match in both files
all(colnames(data)[-c(1,2)] %in% meta$sample)
[1] TRUE
all(colnames(data)[-c(1,2)] == meta$sample)
[1] FALSE

Reorder meta rows so it matches count data colnames

reorder <- match(colnames(data)[-c(1,2)],meta$sample)
reorder
[1] 3 2 1 8 7 6 5 4
meta <- meta[reorder,] 

Create DESeq2Dataset object

dds <- DESeqDataSetFromMatrix(countData = data %>% dplyr::select(-gene_name) %>% column_to_rownames("gene_id") %>% mutate_all(as.integer), 
                              colData = meta %>% column_to_rownames("sample"), 
                              design = ~ condition)

If you have pseudocounts

Load samplesheet with all our metadata from our pipeline

# Load data, metadata and tx2gene and create a txi object
meta <- read_csv("../Data/samplesheet.csv")

Create a list of salmon results

dir <- "../Data/salmon"
tx2gene <- read_table(file.path(dir,"salmon_tx2gene.tsv"), col_names = c("transcript_ID","gene_ID","gene_symbol"))

# Get all salmon results files
files <- file.path(dir, meta$sample, "quant.sf")
names(files) <- meta$sample

Create txi object

txi <- tximport(files, type="salmon", tx2gene=tx2gene, countsFromAbundance = "lengthScaledTPM", ignoreTxVersion = TRUE)

Create dds object

dds <- DESeqDataSetFromTximport(txi,
                                   colData = meta %>% column_to_rownames("sample"), 
                              design = ~ condition)

Exploratory data analysis

Pre-filtering low count genes + PCA & hierarchical clustering - identifying outliers and sources of variation in the data:

Prefiltering low count genes

keep <- rowSums(counts(dds)) > 0
dds <- dds[keep,]

Rlog or vst transformation

# Transform counts for data visualization
rld <- rlog(dds, 
            blind=TRUE)

# vsd <- vst(dds, blind = TRUE)

PCA

Plot PCA

plotPCA(rld, 
        intgroup="condition")

Heatmaps

Extract the rlog matrix from the object

rld_mat <- assay(rld)
rld_cor <- cor(rld_mat) # Pearson correlation between samples
rld_dist <- as.matrix(dist(t(assay(rld)))) #distances are computed by rows, so we need to transponse the matrix

Plot heatmap of correlations

pheatmap(rld_cor, 
         annotation = meta %>% column_to_rownames("sample") %>% dplyr::select("condition"))

Plot heatmap of distances with a new color range

heat.colors <- brewer.pal(6, "Blues") # Colors from the RColorBrewer package (only 6)
heat.colors <- colorRampPalette(heat.colors)(100) # Interpolate 100 colors

pheatmap(rld_dist, 
         annotation = meta %>% column_to_rownames("sample") %>% dplyr::select("condition"),
         color = heat.colors)

Run DESeq2:

Optional step - Re-create DESeq2 dataset if the design formula has changed after QC analysis in include other sources of variation using

# dds <- DESeqDataSetFromMatrix(data, colData = meta, design = ~ covariate + condition)

Run DEseq2

# Run DESeq2 differential expression analysis
dds <- DESeq(dds)

Optional step - Output normalized counts to save as a file to access outside RStudio using

normalized_counts <- counts(dds, normalized=TRUE)

Check the fit of the dispersion estimates

Plot dispersion estimates

plotDispEsts(dds)

Create contrasts to perform Wald testing or the shrunken log2 fold changes between specific conditions

Formal LFC calculation

# Specify contrast for comparison of interest
contrast <- c("condition", "control", "vampirium")

# Output results of Wald test for contrast
res <- results(dds, 
               contrast = contrast, 
               alpha = 0.05)

Shrinkage

# Get name of the contrast you would like to use
resultsNames(dds)
[1] "Intercept"                      "condition_garlicum_vs_control" 
[3] "condition_vampirium_vs_control"
# Shrink the log2 fold changes to be more accurate
res <- lfcShrink(dds, 
                 coef = "condition_vampirium_vs_control", 
                 type = "apeglm")

Output significant results:

# Set thresholds
padj.cutoff <- 0.05

# Turn the results object into a tibble for use with tidyverse functions
res_tbl <- res %>%
  data.frame() %>%
  rownames_to_column(var="gene") %>% 
  as_tibble()

# Subset the significant results
sig_res <- dplyr::filter(res_tbl, 
                  padj < padj.cutoff)

Visualize results: volcano plots, heatmaps, normalized counts plots of top genes, etc.

Function to get gene_IDs based on gene names. The function will take as input a vector of gene names of interest, the tx2gene dataframe and the dds object that you analyzed.

lookup <- function(gene_name, tx2gene, dds){
  hits <- tx2gene %>% dplyr::select(gene_symbol, gene_ID) %>% distinct() %>% 
    dplyr::filter(gene_symbol %in% gene_name & gene_ID %in% rownames(dds))
  return(hits)
}

lookup(gene_name = "TSPAN7", tx2gene = tx2gene, dds = dds)

Plot expression for single gene

plotCounts(dds, gene="ENSG00000156298", intgroup="condition")

Function to annotate all your gene results

res_tbl <- merge(res_tbl, tx2gene %>% dplyr::select(-transcript_ID) %>% distinct(),
                        by.x = "gene", by.y = "gene_ID", all.x = T)

res_tbl

MAplot

plotMA(res)

Volcano plot with labels (top N genes)

## Obtain logical vector where TRUE values denote padj values < 0.05 and fold change > 1.5 in either direction
res_tbl <- res_tbl %>% 
mutate(threshold = padj < 0.05 & abs(log2FoldChange) >= 0.58)
## Create an empty column to indicate which genes to label
res_tbl <- res_tbl %>% mutate(genelabels = "")

## Sort by padj values 
res_tbl <- res_tbl %>% arrange(padj)

## Populate the genelabels column with contents of the gene symbols column for the first 10 rows, i.e. the top 10 most significantly expressed genes
res_tbl$genelabels[1:10] <- as.character(res_tbl$gene[1:10])

head(res_tbl)
ggplot(res_tbl, aes(x = log2FoldChange, y = -log10(padj))) +
  geom_point(aes(colour = threshold)) +
  geom_text_repel(aes(label = genelabels)) +
  ggtitle("Vampirium vs Control") +
  xlab("log2 fold change") + 
  ylab("-log10 adjusted p-value") +
  theme(legend.position = "none",
        plot.title = element_text(size = rel(1.5), hjust = 0.5),
        axis.title = element_text(size = rel(1.25))) 

Heatmap of differentially expressed genes

# filter significant results from normalized counts
norm_sig <- normalized_counts %>% as_tibble(rownames = "gene") %>%
  dplyr::filter(gene %in% sig_res$gene) %>% column_to_rownames(var="gene")
pheatmap(norm_sig, 
         cluster_rows = T, #cluster by expression pattern
         scale = "row", # scale by gene so expression pattern is visible
         treeheight_row = 0, # dont show the row dendogram
         show_rownames = F, # remove rownames so it is more clear
         annotation = meta %>% column_to_rownames(var = "sample") %>% dplyr::select("condition")
         )

Perform analysis to extract functional significance of results: GO or KEGG enrichment, GSEA, etc.

Annotate with annotables

ids <- grch38 %>% dplyr::filter(ensgene %in% res_tbl$gene) 
res_ids <- inner_join(res_tbl, ids, by=c("gene"="ensgene"))

Perform enrichment analysis of GO terms (can be done as well with KEGG pathways)

# Create background dataset for hypergeometric testing using all genes tested for significance in the results
all_genes <- dplyr::filter(res_ids, !is.na(gene)) %>% 
  pull(gene) %>% 
  as.character()

# Extract significant results
sig <- dplyr::filter(res_ids, padj < 0.05 & !is.na(gene))

sig_genes <- sig %>% 
  pull(gene) %>% 
  as.character()
# Perform enrichment analysis
ego <- enrichGO(gene = sig_genes, 
                universe = all_genes,
                keyType = "ENSEMBL",
                OrgDb = org.Hs.eg.db, 
                ont = "BP", 
                pAdjustMethod = "BH", 
                qvalueCutoff = 0.05, 
                readable = TRUE)
ego <- enrichplot::pairwise_termsim(ego)

Visualize result

dotplot(ego, showCategory=50)

emapplot(ego, showCategory = 50)

Cnetplot

## To color genes by log2 fold changes, we need to extract the log2 fold changes from our results table creating a named vector
sig_foldchanges <- sig$log2FoldChange

names(sig_foldchanges) <- sig$gene
## Cnetplot details the genes associated with one or more terms - by default gives the top 5 significant terms (by padj)
cnetplot(ego, 
         categorySize="pvalue", 
         showCategory = 5, 
         foldChange=sig_foldchanges, 
         vertex.label.font=6)

Perform GSEA analysis of KEGG pathways (can be done as well with GO terms)

# Extract entrez IDs. IDs should not be duplicated or NA
res_entrez <- dplyr::filter(res_ids, entrez != "NA" & entrez != "NULL" & duplicated(entrez)==F)

## Extract the foldchanges
foldchanges <- res_entrez$log2FoldChange

## Name each fold change with the corresponding Entrez ID
names(foldchanges) <- res_entrez$entrez

## Sort fold changes in decreasing order
foldchanges <- sort(foldchanges, decreasing = TRUE)
# Run GSEA of KEGG
gseaKEGG <- gseKEGG(geneList = foldchanges, # ordered named vector of fold changes (Entrez IDs are the associated names)
              organism = "hsa", # supported organisms listed below
              pvalueCutoff = 0.05, # padj cutoff value
              verbose = FALSE)

gseaKEGG_results <- gseaKEGG@result
head(gseaKEGG_results)
## Plot the GSEA plot for a single enriched pathway:
gseaplot(gseaKEGG, geneSetID = gseaKEGG_results$ID[1])

## Output images for a single significant KEGG pathway
pathview(gene.data = foldchanges,
              pathway.id = gseaKEGG_results$ID[1],
              species = "hsa",
              limit = list(gene = 2, # value gives the max/min limit for foldchanges
              cpd = 1))
knitr::include_graphics(paste0("./",gseaKEGG_results$ID[1],".png"))

Make sure to output the versions of all tools used in the DE analysis:

sessionInfo()
R version 4.3.3 (2024-02-29)
Platform: x86_64-conda-linux-gnu (64-bit)
Running under: Ubuntu 24.04.2 LTS

Matrix products: default
BLAS/LAPACK: /opt/.pixi/envs/course-env/lib/libopenblasp-r0.3.28.so;  LAPACK version 3.12.0

locale:
 [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8       
 [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8   
 [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C          
[10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C   

time zone: Europe/Berlin
tzcode source: system (glibc)

attached base packages:
[1] stats4    stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
 [1] RColorBrewer_1.1-3          tximport_1.30.0            
 [3] org.Hs.eg.db_3.18.0         AnnotationDbi_1.64.1       
 [5] pathview_1.42.0             DOSE_3.28.1                
 [7] clusterProfiler_4.10.0      annotables_0.2.0           
 [9] pheatmap_1.0.13             ggrepel_0.9.6              
[11] DESeq2_1.42.0               SummarizedExperiment_1.32.0
[13] Biobase_2.62.0              MatrixGenerics_1.14.0      
[15] matrixStats_1.5.0           GenomicRanges_1.54.1       
[17] GenomeInfoDb_1.38.1         IRanges_2.36.0             
[19] S4Vectors_0.40.2            BiocGenerics_0.48.1        
[21] lubridate_1.9.4             forcats_1.0.0              
[23] stringr_1.5.2               dplyr_1.1.4                
[25] purrr_1.1.0                 readr_2.1.5                
[27] tidyr_1.3.1                 tibble_3.3.0               
[29] ggplot2_3.5.2               tidyverse_2.0.0            

loaded via a namespace (and not attached):
  [1] jsonlite_2.0.0          magrittr_2.0.3          farver_2.1.2           
  [4] rmarkdown_2.29          fs_1.6.6                zlibbioc_1.48.0        
  [7] vctrs_0.6.5             memoise_2.0.1           RCurl_1.98-1.17        
 [10] ggtree_3.10.0           htmltools_0.5.8.1       S4Arrays_1.2.0         
 [13] SparseArray_1.2.2       gridGraphics_0.5-1      htmlwidgets_1.6.4      
 [16] plyr_1.8.9              cachem_1.1.0            uuid_1.2-1             
 [19] igraph_2.0.3            lifecycle_1.0.4         pkgconfig_2.0.3        
 [22] gson_0.1.0              Matrix_1.6-1.1          R6_2.6.1               
 [25] fastmap_1.2.0           GenomeInfoDbData_1.2.11 numDeriv_2016.8-1.1    
 [28] digest_0.6.37           aplot_0.2.9             enrichplot_1.22.0      
 [31] ggnewscale_0.5.2        colorspace_2.1-1        patchwork_1.3.2        
 [34] RSQLite_2.4.3           labeling_0.4.3          timechange_0.3.0       
 [37] httr_1.4.7              polyclip_1.10-7         abind_1.4-5            
 [40] compiler_4.3.3          bit64_4.6.0-1           withr_3.0.2            
 [43] S7_0.2.0                BiocParallel_1.36.0     viridis_0.6.5          
 [46] DBI_1.2.3               ggforce_0.5.0           MASS_7.3-60.0.1        
 [49] rappdirs_0.3.3          DelayedArray_0.28.0     HDO.db_0.99.1          
 [52] tools_4.3.3             ape_5.8-1               scatterpie_0.2.6       
 [55] glue_1.8.0              nlme_3.1-165            GOSemSim_2.28.0        
 [58] grid_4.3.3              shadowtext_0.1.6        reshape2_1.4.4         
 [61] fgsea_1.28.0            generics_0.1.4          gtable_0.3.6           
 [64] tzdb_0.5.0              data.table_1.17.8       hms_1.1.3              
 [67] tidygraph_1.3.0         XVector_0.42.0          pillar_1.11.0          
 [70] emdbook_1.3.14          vroom_1.6.5             yulab.utils_0.2.1      
 [73] splines_4.3.3           tweenr_2.0.3            treeio_1.26.0          
 [76] lattice_0.22-7          bit_4.6.0               tidyselect_1.2.1       
 [79] GO.db_3.18.0            locfit_1.5-9.12         Biostrings_2.70.1      
 [82] knitr_1.50              gridExtra_2.3           xfun_0.53              
 [85] graphlayouts_1.2.2      KEGGgraph_1.62.0        stringi_1.8.7          
 [88] lazyeval_0.2.2          ggfun_0.2.0             yaml_2.3.10            
 [91] evaluate_1.0.5          codetools_0.2-20        bbmle_1.0.25.1         
 [94] ggraph_2.2.1            qvalue_2.34.0           Rgraphviz_2.46.0       
 [97] graph_1.80.0            ggplotify_0.1.3         cli_3.6.5              
[100] systemfonts_1.2.3       Rcpp_1.1.0              coda_0.19-4.1          
[103] png_0.1-8               bdsmatrix_1.3-7         XML_3.99-0.17          
[106] parallel_4.3.3          blob_1.2.4              bitops_1.0-9           
[109] mvtnorm_1.2-6           apeglm_1.24.0           viridisLite_0.4.2      
[112] tidytree_0.4.6          ggiraph_0.8.12          scales_1.4.0           
[115] crayon_1.5.3            rlang_1.1.6             cowplot_1.2.0          
[118] fastmatch_1.1-6         KEGGREST_1.42.0