Differential Gene Expression
Bioinformatics Core Facility CECAD
2026-11-24
git clone https://github.com/CECADBioinformaticsCoreFacility/Intermediate_R_Course_2026.git
https://cecadbioinformaticscorefacility.github.io/Advanced_R_Course_2026/
Session 2:: Differential Gene Expression:: Basics
First of all, we convert the column names to all-lowercase, to avoid case issues:
Then we discard genes with a total count < 10, as was done in the paper:
(more on that later by Ali)browseVignettes("DESeq2")We do not have the colData – but it is actually easy to create this matrix starting from the count matrix column names:
# 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"
# 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
The simplest way to deal with it: subset!
The second-simplest way: group!
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.
At this point we can have the available test results listed:
We want to see the genotype effect …
… in a nice table (see next slide):
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.
Observe:
The lfcShrink() function of DESeq2
?lfcShrink and the DESeq2 vignette for available shrinkage methodsThe bimodality is much more clear after shrinkage – this is really unusual
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.
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:
hidden factors which can be identified and included in the model?poor clustering of expected groups suggest experimental issues?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 log2FoldChangemeanSdPlot: tries to transform the count distribution such that the standard deviation is ~identical for ~all of the genes
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")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
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>
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.
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
}There is very clear structure in the unlabelled dataset …
… but genotype is more or less unrelated to this global structure!
What about the other variables?
Exercises 1+2:
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)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")
)
)Then plot it:
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.
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
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()
}Exercise 3:
Exercise 4:
different tissues have very different transcriptomes (as can be expected!)sensible to analyse them one at a time,