R Advanced Course 2026

Differential Gene Expression

Ulrike Göbel

Bioinformatics Core Facility CECAD

2026-11-24

Slides & Code

  • [f] Full screen
  • [o] Slide Overview
  • [c] Notes
  • [h] help

git repo

R-Basic


Clone repo

git clone https://github.com/CECADBioinformaticsCoreFacility/Intermediate_R_Course_2026.git


Slides Directly

https://cecadbioinformaticscorefacility.github.io/Advanced_R_Course_2026/

Session 2:: Differential Gene Expression:: Basics

The Practice Dataset

The Practice Dataset

 

data_dir <- "." ## the current folder
matrix_file <- "GSE234563_Matrix.txt.gz"

# download it ..
#download.file(
#  url="https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE234563&format=file&file=GSE234563%5FMatrix%2Etxt%2Egz",
#  destfile=matrix_file
#)
# .. read it:
M <- read.table(fs::path(data_dir,
                         matrix_file),
                header = TRUE,
                sep = "\t",
                quote = ""
                )
# .. this is a huge matrix!
dim(M)
[1] 40946   144
# .. display the first 6 rows (output next page):
dt <- DT::datatable(M |> head())
dt

The Practice Dataset

Count Matrix Preprocessing

 

First of all, we convert the column names to all-lowercase, to avoid case issues:

colnames(M) <- tolower(colnames(M))

 

Then we discard genes with a total count < 10, as was done in the paper:

min_count <- 10

M <- M[rowSums(M) >= min_count,] 
#M <- M[(rowSums(M) >= min_count) &  ## for testing
#      apply(M,1,function(x) !any(x >= 10^3)) ,]

nrow(M)
[1] 32904

 

Finally we map matrix entries with fractional digits to the next higher integer value 
(the differential expression analysis expects integer counts):

M <- ceiling(M)

Introducing the DESeq2 Package

  • A Bioconductor package for Differential Gene Expression (DGE) analysis
  • Based on sophisticated mathematical theory (more on that later by Ali)
  • But its high-level functions allow to run an entire DGE analysis in three steps!
  • See browseVignettes("DESeq2")
  • Read the original paper
library(DESeq2)

browseVignettes("DESeq2")

Setting Up the Input for DESeq2

Setting Up the Input for DESeq2

Setting Up the Input for DESeq2

We do not have the colData – but it is actually easy to create this matrix starting from the count matrix column names:

# Step 1: split the count matrix column names at "_"
#         (result: a list of vectors, where each vector holds the fragments extracted from one name)
colData <- strsplit(colnames(M),"_") 

head(colData, n=2) 
[[1]]
[1] "old"       "female"    "creer"     "intestine" "1"        

[[2]]
[1] "old"       "female"    "creer"     "intestine" "2"        

 

# Step 2: make a matrix, in which each vector from Step 1 is a row
colData <- Reduce(rbind,colData)

head(colData, n=2) 
     [,1]  [,2]     [,3]    [,4]        [,5]
init "old" "female" "creer" "intestine" "1" 
     "old" "female" "creer" "intestine" "2" 

Setting Up the Input for DESeq2

# Step 3: We know what the row and column names should be, so let's set them:
dimnames(colData) <- list(colnames(M),
c("age","sex","genotype","tissue","replicate")
                          )
head(colData, n=2) 
                             age   sex      genotype tissue      replicate
old_female_creer_intestine_1 "old" "female" "creer"  "intestine" "1"      
old_female_creer_intestine_2 "old" "female" "creer"  "intestine" "2"      

Setting Up the Input for DESeq2

# Step 4: Add two grouping factors, which combine the levels of > 1 variable:  

colData <- 
  colData |> as.data.frame() |> 
  tidyr::unite("background",  c(age,sex,tissue),
               sep=".",remove=FALSE) |> 
  tidyr::unite("group",c(age,sex,tissue,genotype), 
               sep=".",remove=FALSE)


# Have look at the result:
head(colData,n=2) 
                                       background                      group
old_female_creer_intestine_1 old.female.intestine old.female.intestine.creer
old_female_creer_intestine_2 old.female.intestine old.female.intestine.creer
                             age    sex genotype    tissue replicate
old_female_creer_intestine_1 old female    creer intestine         1
old_female_creer_intestine_2 old female    creer intestine         2

This is a HUGE Matrix !

This is a HUGE Matrix !

The simplest way to deal with it: subset!

This is a HUGE Matrix !

The second-simplest way: group!

A Bold Try: Model the Full Data With Genotype Only

The most simple question we can ask to our data matrix is:  
Is the nmrHas transgene effect strong enough to manifest irrespective of age, sex and tissue?
Starting from this question, we will dig deeper both into the dataset and into modeling.  

 

library(DESeq2)

dds_genotype <-
  # High level step 1: set up the object structure
    DESeqDataSetFromMatrix(countData = M,
                           colData = colData,
                           design= ~ 1 + genotype 
                           ) |>
  # High level step 2: "do the math" (--> Ali!)
  #                    size factors factors,
  #                    dispersion estimates,
  #                    statistical tests ...
    DESeq()

At this point we can have the available test results listed:

resultsNames(dds_genotype)
[1] "Intercept"                 "genotype_nmrhas2_vs_creer"

A Bold Try: Model the Full Data With Genotype Only

We want to see the genotype effect …

res_genotype <- 
    results(dds_genotype, 
            name="genotype_nmrhas2_vs_creer"
            )
saveRDS(res_genotype, file="res_genotype.rds")

… in a nice table (see next slide):

dt <- DT::datatable(
           res_genotype |> as.data.frame() |>
           dplyr::filter(!is.na(padj), padj <= 0.05) |>
           dplyr::arrange(padj),

           options=list(scrollY="500px")
     ) 

# convert numeric columns to scientific notation
dt <- dt |>
      DT::formatSignif(
           sapply(dt$x$data, is.numeric),
           digits=2
      )

A Bold Try: Model the Full Data With Genotype Only

MA Plot and Shrinkage

The plotMA() function of DESeq2 draws a scatterplot of the mean normalized counts against the log2FoldChange values. It helps to see the significant genes in the context of the entire dataset, and notably also to pinpoint unusual features of the entire count distribution.

plotMA(res_genotype) 

Observe:

  • the number of significant genes is REALLY small compared to the entire distribution
  • there is a slight bimodality in the point cloud – this is unusual

MA Plot and Shrinkage

The lfcShrink() function of DESeq2

  • is an alternative to results()
  • shifts noisy, unreliable log2FoldChange values towards zero
  • see ?lfcShrink and the DESeq2 vignette for available shrinkage methods
res_genotype_shrunken <-
  lfcShrink(dds_genotype, 
            ## MIND: "coef", 
            ##       not "name" as in results() !
            coef="genotype_nmrhas2_vs_creer", 
            type="ashr")

plotMA(res_genotype_shrunken)

The bimodality is much more clear after shrinkage – this is really unusual

Why So Few Significant Genes?

Why So Few Significant Genes?

I had on purpose omitted a step which should really be done in the beginning: Get to know the sources of variability in your count matrix!  

All known such sources should be either eliminated or stated in the design given to DESeq2. Otherwise the neglected factors will be treated as random variance by the model and this may mask a real effect.

Why So Few Significant Genes?

Principal Component Analysis (PCA) projects the transcriptome of each sample onto a point on a two-dimensional canvas, such that the among-sample variance is maximal.

It helps to answer questions like:

  • Do the samples cluster as your hypotheses suggest?
  • If not, does the cluster structure suggest hidden factors which can be identified and included in the model?
  • Or does poor clustering of expected groups suggest experimental issues?

Why So Few Significant Genes?

Heatmaps display the transcriptomes directly as colored matrix columns. Clustering the columns can identify groups of samples with similar global gene expression, like PCA.

Boxplots of the matrix columns visualize the distributional properties of the per-sample counts.

… and of course the diagnostic tools of the DESeq2 package:

  • MA plot: graphs the mean normalized count agains the log2FoldChange
  • meanSdPlot: tries to transform the count distribution such that the standard deviation is ~identical for ~all of the genes
    • DESeq2’s differential gene expression analysis assumes that this is possible
    • if it is not possible, then the DGE results will likely be misleading!

Preparation for PCA

DESeq2’s vst() function implements this variance stabilizing transformation. 
It is meant to eliminate the increase in variance with count which is natural to count data.

We will use vst() to transform the input to PCA and heatmap functions.

# The "blind" parameter tells the function NOT to use the input object's
# model formula for identifying "valid" (expected) variation. 
# We do this here because we have not yet found an optimal formula.
# NOTE that if we have a trusted formula and want to use vst() to 
# prepare an object for downstream analysis, then blind=FALSE should 
# be used.
vsd_blind <- vst(dds_genotype, 
                 blind=TRUE
                )
saveRDS(vsd_blind,file="vsd_blind.rds")

A Barebones PCA Plotting Function

The DESeq2 package also provides a function plotPCA(), which executes a Principal Components Analysis and plots the result. It is an implementation of a generic function BiocGenerics::plotPCA. To see its code, type

# The triple colon operator shows non-exported code of a package
DESeq2:::plotPCA.DESeqTransform
function (object, intgroup = "condition", ntop = 500, returnData = FALSE, 
    pcsToUse = 1:2) 
{
    message(paste0("using ntop=", ntop, " top features by variance"))
    rv <- rowVars(assay(object))
    select <- order(rv, decreasing = TRUE)[seq_len(min(ntop, 
        length(rv)))]
    pca <- prcomp(t(assay(object)[select, ]))
    percentVar <- pca$sdev^2/sum(pca$sdev^2)
    if (!all(intgroup %in% names(colData(object)))) {
        stop("the argument 'intgroup' should specify columns of colData(dds)")
    }
    intgroup.df <- as.data.frame(colData(object)[, intgroup, 
        drop = FALSE])
    group <- if (length(intgroup) > 1) {
        factor(apply(intgroup.df, 1, paste, collapse = ":"))
    }
    else {
        colData(object)[[intgroup]]
    }
    pcs <- paste0("PC", pcsToUse)
    d <- data.frame(V1 = pca$x[, pcsToUse[1]], V2 = pca$x[, pcsToUse[2]], 
        group = group, intgroup.df, name = colnames(object))
    colnames(d)[1:2] <- pcs
    if (returnData) {
        attr(d, "percentVar") <- percentVar[pcsToUse]
        return(d)
    }
    ggplot(data = d, aes_string(x = pcs[1], y = pcs[2], color = "group")) + 
        geom_point(size = 3) + xlab(paste0(pcs[1], ": ", round(percentVar[pcsToUse[1]] * 
        100), "% variance")) + ylab(paste0(pcs[2], ": ", round(percentVar[pcsToUse[2]] * 
        100), "% variance")) + coord_fixed()
}
<bytecode: 0x55abd489ea98>
<environment: namespace:DESeq2>

A Barebones PCA Plotting Function

I provide a simplified version of it, which removes much of the pre-processing code. 

Instead, the function relies on the dot-dot-dot argument (...), 
which is a list of parameter=argument pairs.  

It is kind of a self-service store for functions called in the 
body of a function.  

 

f2 <- function(a) cat(a,"\n")
f1 <- function(i,j) f2() 

## Simply passing a value for f2's "a" 
## through f1's interface fails
f1(i=1,j=2,a="hello world!")
Error in f1(i = 1, j = 2, a = "hello world!"): unused argument (a = "hello world!")
## but if f1() has dot-dot-dot in its interface 
## and passes it on to f2() ---
f1 <- function(i,j, ...) f2(...)
## --- it succeeds! 
f1(i=1,j=2,a="hello world!")
hello world! 

A Barebones PCA Plotting Function

plotPCA2 <-
    
function (object, ntop = 500, returnData = FALSE,
          pcsToUse=c(x=1,y=2),
          pointSize=3,
          hjust=-0.75,vjust=0.5,
          just_print_select=FALSE,
          print_labels=FALSE, 
          use_coord_fixed=FALSE,
          ...
          )  {

    ## Get the ntop most highly variable genes:  
    rv <- rowVars(assay(object))
    select <- order(rv, decreasing = TRUE)[seq_len(min(ntop, 
                                                       length(rv)))]
    if(just_print_select) {
        return(select)
    }
    
    ## Compute the PCA:
    pca <- prcomp(t(assay(object)[select, ]))
    percentVar <- pca$sdev^2/sum(pca$sdev^2)

    d <- data.frame(pca$x[, pcsToUse[1]], pca$x[, pcsToUse[2]], 
                    as.data.frame(colData(object)),
                    name = colnames(object))
    colnames(d)[1:2] <- paste("PC",pcsToUse,sep="")

    if (returnData) {
        attr(d, "percentVar") <- percentVar[pcsToUse]
        return(d)
    }
    
    ## Draw the scatterplot:
    p <- 
        ggplot(data = d,
               aes_string(x = paste("PC",pcsToUse["x"],sep=""),
                          y = paste("PC",pcsToUse["y"],sep="")
                          )
        ) + 
        geom_point(mapping = aes(
                      ...
                   ),
                   size = pointSize  ## set last, to override any "size"
                                     ## argument set inside aes()
                   
        ) +
        xlab(paste0("PC",pcsToUse["x"],": ", round(percentVar[pcsToUse["x"]] * 100), "% variance",sep="")) + 
        ylab(paste0("PC",pcsToUse["y"],": ", round(percentVar[pcsToUse["y"]] * 100), "% variance",sep=""))

    ## Add point labels if desired 
    if(print_labels) {
        p <- p +  geom_text(aes(label=rownames(d),hjust=hjust, vjust=vjust))
    }
    
    ## Set the ratio of the units on x and y axis to 1:
    if(use_coord_fixed) { 
        p <- p + coord_fixed() 
    }

    p
}

What Drives the Structure?

plotPCA2(vsd_blind,
         ntop=500, 
         pcsToUse=c(x=1,y=2))

There is very clear structure in the unlabelled dataset …

What Drives the Structure?

plotPCA2(vsd_blind,
         color=genotype,
         ntop=500, 
         pcsToUse=c(x=1,y=2) 
         )  

… but genotype is more or less unrelated to this global structure!

What about the other variables?

What Drives the Structure?

plotPCA2(vsd_blind,
         ntop=1000, 
         color = sex,
         shape = age, 
         alpha = genotype,
         pcsToUse=c(x=1,y=2) 
         
         ) + 
  # mark empty-vector samples as transparent,
  # NMR transgene samples as opaque:
  scale_alpha_manual(values = c("creer" = 0.3, 
                                "nmrhas2" = 1)) 

What Drives the Structure? – Your Turn!

 

Exercises 1+2:

  • After variance stabilization, the standard deviation of the counts should be roughly independent of their mean. Can this be achieved with the full dataset?
  • Visualize the distribution of the experimental variables on the PCA plot
    • Do any of the variables correlate strongly with the PCA structure?

What Drives the Structure?

plotPCA2(vsd_blind,
         ntop=500, 
         color = sex,
         alpha = genotype,
         pcsToUse=c(x=1,y=2) 
         
         ) + 
  # mark empty-vector samples as transparent,
  # NMR transgene samples as opaque:
  scale_alpha_manual(values = c("creer" = 0.3, 
                                "nmrhas2" = 1))

What Drives the Structure?

plotPCA2(vsd_blind,
         ntop=500, 
         color = paste(sex,age,sep="."),
         alpha = genotype,
         pcsToUse=c(x=1,y=2) 
         
         ) + 
  # mark empty-vector samples as transparent,
  # NMR transgene samples as opaque:
  scale_alpha_manual(values = c("creer" = 0.3, 
                                "nmrhas2" = 1))

What Drives the Structure?

plotPCA2(vsd_blind,
         ntop=500, 
         color = tissue,
         shape = paste(sex, age, sep="."),
         alpha = genotype,
         pcsToUse=c(x=1,y=2) 
         
         ) + 
  # mark empty-vector samples as transparent,
  # NMR transgene samples as opaque:
  scale_alpha_manual(values = c("creer" = 0.3, 
                                "nmrhas2" = 1))

What Drives the Structure?

plotPCA2(vsd_blind,
         ntop=1000, 
         color = tissue,
         shape = paste(sex, age, sep="."),
         alpha = genotype,
         pcsToUse=c(x=1,y=2) 
         
         ) + 
  # mark empty-vector samples as transparent,
  # NMR transgene samples as opaque:
  scale_alpha_manual(values = c("creer" = 0.3, 
                                "nmrhas2" = 1))

Heatmap of the 500 Most Highly Expressed Genes

 

selected <- 
  order(rowMeans(counts(dds_genotype,
                        normalized=TRUE)
                ),
        decreasing=TRUE)[1:500]

df <- (colData(dds_genotype) |>
       as.data.frame())[,c("age",
                           "sex",
                           "genotype",
                           "tissue")]

pheatmap(assay(vsd_blind)[selected,], 
         cluster_rows=FALSE, 
         show_rownames=FALSE,
         show_colnames=FALSE,
         cluster_cols=TRUE, 
         annotation_col=df)

  • With the exception of spleen and WAT, all tissues have strongly distinct expression patterns
  • Both levels of the genotype factor are compatible with any of these global patterns

Boxplots of the Per-Sample Count Distributions

We want to plot the raw and normalized count distributions of each sample side by side, using ggplot(). For this we have to “melt” the log10 transformed matrices:

df <-
    rbind(reshape2::melt(log10(counts(dds_genotype,normalized=FALSE)+1)) |>
          mutate(mode="raw"),

          reshape2::melt(log10(counts(dds_genotype,normalized=TRUE)+1)) |>
          mutate(mode="normalized")
          ) |>
  # rename to make variable names more meaningful:
    dplyr::rename(gene=Var1, sample=Var2, count=value) |>
  
  # remove the trailing sample ID to create a common ID for all replicates
  # of a given factor level combination:
    mutate(group=sub("_\\d+$","",sample)) |>
  
  # ggplot needs to know the order of sub-plots ("raw" should come first)
    mutate(mode = factor(mode,
                         levels=c("raw","normalized")
                         )
         )

Boxplots of the Per-Sample Count Distributions

Then plot it:

ggplot(df,
       # aes(y=count,x=sample,fill=group) ## too dense
       aes(x=count,y=sample,fill=group) 
       ) +
    geom_boxplot(show.legend=FALSE) +
    facet_wrap(vars(mode),ncol=2) +
    theme_classic() +
    theme(axis.text=element_text(size=2)) #,
          #axis.text.x = element_text(angle = 90, 
          #                           vjust = 0.5,
          #                           hjust=1))

Boxplots of the Per-Sample Count Distributions

Boxplots of the Per-Sample Count Distributions

  • While raw counts may differ in shape and location between samples, these differences should go away after a successful DESeq2 “median of ratios” normalization.

  • Failure to normalize indicates an issue!.  

  • Here, the reason is very likely the fact that the samples come from different tissues, with very different gene expression signatures. DESeq2’s approach to use the geometric expression mean over all samples of each gene as a pseudo-reference count may not be justified in this case.

Subset the Dataset to One Tissue At a Time

The below function accepts a single metadata variable use_var and a vector use_levels of its levels. It returns a new dds object, which

  • contains only samples from the selected levels of the selected variable
  • has appropriate sizeFactors
  • no longer contains genes whose total count is less than min_count after sample restriction
  • no longer contains/needs use_var – all samples are now from use_var by definition

 

subset_dds <- 
  function(dds, use_var, use_levels, 
           design = NULL, min_count=10) {
    
    M <- counts(dds,normalize=FALSE)
    colData <- colData(dds)
    
    if(is.null(design)) { # use the design of the input object
      use_design <- design(dds) 
    } else { # set a custom design
      use_design = design
    }
    
    j <- colData[,use_var] %in% use_levels ## samples to keep
    i <- rowSums(M[,j]) >= min_count       ## rows to keep
    
    DESeqDataSetFromMatrix(countData = M[i,j],
                           colData = colData[j,] |> ## natively a DFrame ! 
                             as.data.frame() |>
                             dplyr::select(-!!use_var),
                           design= as.formula(use_design)
    ) |> DESeq()
  }

Subset the Dataset to One Tissue At a Time – Your Turn!

Exercise 3:

  • For each level of the tissue variable, 
    construct a dds object with samples exclusively from this level
  • Collect the per-tissue dds objects in a list, and save it in an RDS file for later use
  • For each such dds object
    • run vst(object) |> plotPCA2()
    • mark sex on the plot by color, age by shape, and genotype by alpha
  • Can we now see more fine structure?

Exercise 4:

  • For each per-tissue dds object,
    • draw an MA plot with and without shrinkage
    • tabulate the number of significant genes (padj <= 0.05) with and without shrinkage
    • Is there evidence of tissue-specific gene expression programs?

What Did We Learn in Part 1?

  • The different tissues have very different transcriptomes (as can be expected!)
  • It is therefore sensible to analyse them one at a time,
  • unless (-> Part 2):
    • we include all experimental variables in the model formula!

Before We Go On …

… Ali On the Mathematics Behind DESeq2!