1 Introduction

1.1 Aim of the exercise

The goal of this exercise is to introduce you to Bioconductor and some basic analyses on raw read counts including normalization, transformation, visualization and differential expression. You will also examine the variance and the dispersion in RNA-seq data - two concepts that are needed to understand how DESeq2 and edgeR pipelines work for differential expression.

1.2 R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com. When you click the Knit button in Rstudio a document will be generated that includes both content as well as the output of any embedded R code chunks within the document.

1.3 Bioconductor

1.3.1 About Bioconductor

Bioconductor project host several open source R packages that are designed for the analysis of biological assays. The main tools edgeR and DESeq2 are part of Bioconductor repository. R packages from Bioconductor comes with vignettes that are designed to run a full analysis for each tool deposited there. Vignettes and detailed documents about how to use the R package is of great help for anyone who performs bioinformatics analysis. For example, both edgeR and DESeq2 has great manuals (perhaps the best in Bioconductor).

2 Data

The exercise is based on the following two sources:

Read counts come from a study about the profiling of poly(A)-selected RNA in LNCaP cells before and after androgen stimulation. Briefly, the study used LNCaP cells, which are androgen-sensitive human prostate adenocarcinoma cells, and treated the cells with DHT (endogenous androgen sex steroid and hormone) and with a mock treatment as the control. The poly-A RNAs were captured and sequenced on 7 lanes.

2.1 Read count table

file_url <- 'http://davetang.org/eg/pnas_expression.txt'
data <- read.table(file_url, header=T, sep="\t", stringsAsFactors=F, row.names=1)
head(data)
##                 lane1 lane2 lane3 lane4 lane5 lane6 lane8  len
## ENSG00000215696     0     0     0     0     0     0     0  330
## ENSG00000215700     0     0     0     0     0     0     0 2370
## ENSG00000215699     0     0     0     0     0     0     0 1842
## ENSG00000215784     0     0     0     0     0     0     0 2393
## ENSG00000212914     0     0     0     0     0     0     0  384
## ENSG00000212042     0     0     0     0     0     0     0   92
rmCol <- 8 # column "len" with no count information
rmZero <- rowSums(data[,-rmCol])>0 # genes zero counts across all lanes
table(rmZero)
## rmZero
## FALSE  TRUE 
## 15558 21877
data_subset <- data[rmZero,-rmCol]
Question: How many genes have more than zero expression?
Click for answer 21877 genes have some expression from at least one lane

3 Key concepts about DGE analysis

3.1 Counts per million (CPM) normalization

data_subset_cpm <- data_subset
colSums(data_subset_cpm)
##   lane1   lane2   lane3   lane4   lane5   lane6   lane8 
##  978576 1156844 1442169 1485604 1823460 1834335  681743
norm_cpm <- function(x){
x * 1000000 / sum(x)
}
data_subset_cpm <- apply(data_subset_cpm, 2, norm_cpm)
colSums(data_subset_cpm)
## lane1 lane2 lane3 lane4 lane5 lane6 lane8 
## 1e+06 1e+06 1e+06 1e+06 1e+06 1e+06 1e+06

3.2 Mean and variance of CPM normalized read counts

## Basic statistics
mock_cols <- 1:4 # Column ID for mock treated samples
dht_cols <- 5:7  # Column ID for DHT treated samples
mock_var <- apply(data_subset_cpm[,mock_cols], 1, var)   # Variance for mock group
mock_mean <- apply(data_subset_cpm[,mock_cols], 1, mean) # Mean for mock group
dht_var <- apply(data_subset_cpm[,dht_cols], 1, var)     # Variance for DHT group
dht_mean <- apply(data_subset_cpm[,dht_cols], 1, mean)   # Mean for DHT group
cor(mock_mean, mock_var, method="spearman") # Mean-Variance correlation in mock group
## [1] 0.9353861
cor(dht_mean, dht_var, method="spearman")   # Mean-Variance correlation in DHT group
## [1] 0.9139193
## Plot mean-variance trends (mock)
mock <- as.data.frame(cbind(mock_mean, mock_var))
# Linear scale
ggplot(mock, aes(mock_mean, mock_var)) + 
  geom_point() + 
  geom_smooth(method="loess")
## `geom_smooth()` using formula = 'y ~ x'

# Log2 scale
ggplot(mock, aes(mock_mean, mock_var)) + 
  geom_point() + 
  geom_smooth(method="loess") + 
  scale_x_continuous(trans='log2') + 
  scale_y_continuous(trans='log2') + 
  labs(x = 'mock_mean (log2 scale)', y = 'mock_var (log2 scale)')
## `geom_smooth()` using formula = 'y ~ x'

## Plot mean-variance trends (DHT)
dht <- as.data.frame(cbind(dht_mean, dht_var))
# Linear scale
ggplot(dht, aes(dht_mean, dht_var)) + 
  geom_point() + 
  geom_smooth(method="loess")
## `geom_smooth()` using formula = 'y ~ x'

# Log2 scale
ggplot(dht, aes(dht_mean, dht_var)) + 
  geom_point() + 
  geom_smooth(method="loess") + 
  scale_x_continuous(trans='log2') + 
  scale_y_continuous(trans='log2') + 
  labs(x = 'dht_mean (log2 scale)', y = 'dht_var (log2 scale)')
## `geom_smooth()` using formula = 'y ~ x'

Question: How are mean and variance correlated?
Click for answer The mean and variance of gene expression is correlated; the higher the expression, the higher the variance.
Question How do mean and variance differ between Control and DHT treatment samples?
Click for answer

The gene with the highest variance in the DHT treatment samples is almost ten fold (max(dht_var)/max(mock_var)) higher than the gene with the highest variance in the mock samples.

  max(dht_var)/max(mock_var)
  ## [1] 8.572825

3.3 Gene dispersion

Assume that you have 2 genes with the following counts:

# Create simple gene count data
simple_counts <- t(data.frame(Gene_1 = c(1000, 1010, 990, 1000), Gene_2 = c(10, 20, 0, 10)))
simple_counts
##        [,1] [,2] [,3] [,4]
## Gene_1 1000 1010  990 1000
## Gene_2   10   20    0   10
# Calculate variance
simple_vars <- apply(simple_counts, 1, var)
simple_vars
##   Gene_1   Gene_2 
## 66.66667 66.66667
# Calculate % fluctuation from mean
perc_fluctuate <- function(x){
  ((x-mean(x))/mean(x)) * 100
}
simple_fluc <- apply(simple_counts, 1, perc_fluctuate)
t(simple_fluc)
##        [,1] [,2] [,3] [,4]
## Gene_1    0    1   -1    0
## Gene_2    0  100 -100    0

Although the variance of these two genes are exactly the same, Gene_1 has 1% fluctuations around mean, while Gene_2 has 100% fluctuations around mean. Clearly, Gene_2 is more variable and this is handled by dispersion estimations. Dispersion estimation is sophisticated, however most modern tools like edgeR and DESeq2 handles it automatically.

The bigger dispersion means more variability across genes. For instance, if you estimate dispersion as 0.19, biological coefficient of variation (BCV, square root of dispersion) is equal to 0.44. This means that the expression values vary up and down by 44% between replicates.

Let’s make a comparison with real data with manually calculating the CPMs and mean expression values.

d <- data[rmZero,-rmCol]
# Working only with "mock" samples for simplicity. 
# In real life, we include all the samples for better dispersion estimation (below: estimateDispersion)
d <- d[,mock_cols] 
group <- c(rep("mock",4))
d.e <- DGEList(counts = d, group=group)

# calculate edgeR’s average log2(CPM) and tagwise dispersion
d.e <- calcNormFactors(d.e)
d.e <- estimateCommonDisp(d.e, verbose=T)
## Disp = 0.01932 , BCV = 0.139
d.e <- estimateTagwiseDisp(d.e)
summary(d.e$tagwise.dispersion)
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
## 0.0003019 0.0209960 0.0536757 0.1563791 0.1994373 1.2338966
# sanity check between edgeR’s average log2 cpm calculations versus our own
cor(d.e$AveLogCPM, log2(mock_mean), method="spearman")
## [1] 0.9999541
plot(d.e$AveLogCPM, log2(mock_mean), pch='.')

Now, we will use edgeR pipeline to calculate average expression and dispersion estimates.

# plot the tagwise (gene-wise) dispersion against the average log2(CPM)
d.df <- data.frame(AveLogCPM = d.e$AveLogCPM, Dispersion  = d.e$tagwise.dispersion)
ggplot(d.df, aes(AveLogCPM, Dispersion)) + 
  geom_point() + 
  geom_smooth(method="loess")
## `geom_smooth()` using formula = 'y ~ x'

Question: The square root of the negative binomial dispersion is the biological coefficient of variation (BCV) across the replicate samples. So how large is the variability of the normalized read counts in the (1) mock samples and (2) DHT treatment samples?
Click for answer The biological variability (BCV) of (1) mock samples is 13.9% and (2) DHT treatment samples is 14.8%. Note that you need to calculate the BCV of DHT treatment samples by yourself ;)
Question: Are edgeR’s average log2-CPM calculation and our own log2 CPM the same?
Click for answer edgeR’s average log2-CPM calculations and our own are the same despite of the low counts.
Question: How are tagwise (gene-wise) dispersion and the average log2 CPM (expression level) correlated?
Click for answer In the real RNA-seq data we observe that the higher the expression, the lower the tagwise dispersion.

3.4 Model read counts as Poisson distribution

Let’s simulate counts that follow a Poisson distribution.

set.seed(31)
sim <- t(sapply(dht_mean, rpois, n=4))
sim_mean <- apply(sim, 1, mean)
sim_var <- apply(sim, 1, var)
cor(sim_mean, sim_var, method="spearman")
## [1] 0.9446539
sim.df <- as.data.frame(cbind(sim_mean, sim_var))
ggplot(sim.df, aes(sim_mean, sim_var)) + 
  geom_point() + 
  geom_smooth()
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

ggplot(sim.df, aes(sim_mean, sim_var)) + 
  geom_point() + 
  geom_smooth() + 
  scale_x_continuous(trans='log2') + 
  scale_y_continuous(trans='log2')
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

Question: How does the mean versus variance plot look for counts that follow a Poisson distribution?
Click for answer The mean versus the variance scatter plot of data simulated from a Poisson distribution is more symmetrical than real data.

Now, we will use edgeR pipeline for the simulated counts to calculate average expression and dispersion estimates.

sim.e <- DGEList(counts = sim, group=c(rep("mock",2),c(rep("dht", 2))))

# calculate edgeR’s average log2(CPM) and tagwise dispersion
sim.e <- calcNormFactors(sim.e)
sim.e <- estimateCommonDisp(sim.e, verbose=T)
## Disp = 1e-04 , BCV = 0.01
sim.e <- estimateTagwiseDisp(sim.e)
summary(sim.e$tagwise.dispersion)
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
## 1.571e-06 1.571e-06 1.571e-06 1.796e-03 4.838e-03 6.434e-03
# sanity check between edgeR’s average log2 cpm calculations versus our own
cor(sim.e$AveLogCPM, log2(sim_mean), method="spearman")
## [1] 0.9998214
plot(sim.e$AveLogCPM, log2(sim_mean), pch='.')

# plot the tagwise (gene-wise) dispersion against the average log2(CPM)
sim.df <- as.data.frame(cbind(sim.e$AveLogCPM, sim.e$tagwise.dispersion)); colnames(sim.df) <- c("AveLogCPM", "Dispersion")
ggplot(sim.df, aes(AveLogCPM, Dispersion)) + geom_point() + geom_smooth(method="loess")
## `geom_smooth()` using formula = 'y ~ x'

Question: How are the average log2-CPM calculated by edgeR and log2 mean raw count of the simulated data correlated?
Click for answer There is very high correlation despite of low counts.
Question: How are tagwise (gene-wise) dispersion and the average log2-CPM (expression level) correlated in the count data from the Poisson distribution?
Click for answer There is no dependency of dispersion and mean in the count data following the theoretical Poisson distribution.

3.5 Filtering counts

Genes with low counts across libraries provide little evidence for differential expression. Because,

  • Biological aspect: The gene expression level should be at a certain minimal level before it is transcribed into proteins
  • Statistical aspect: It is presumed that the expression difference between the genes with low counts are not relevant; therefore, including them in multiple testing would inflate the type-1 error. If less statistical tests are performed, then the correction for multiple testing becomes less stringent.

One should consider removing the lowly expressed genes before proceeding with differential analysis. There are different strategies on filtering lowly expressed genes. For example:

  • DESeq2: Uses “independent” filtering using filter_p function from genefilter R package.
  • edgeR: Uses internal function filterByExprto remove lowly expressed genes across groups of interest.

Examples of these steps are provided below for each analysis pipeline.

4 DESeq2 differential expression analysis

4.1 Read count matrix

d <- data[,-rmCol]
sample_info <- data.frame(condition = c(rep("mock",4),rep("dht",3)), row.names = colnames(d))
sample_info
##       condition
## lane1      mock
## lane2      mock
## lane3      mock
## lane4      mock
## lane5       dht
## lane6       dht
## lane8       dht
#create DE dataset in DESeq2
DESeq.ds <- DESeqDataSetFromMatrix(countData = d, colData = sample_info, design = ~ condition)

4.2 Pre-filtering

#pre-filtering counts: although not necesseary, it will increase the speed due to less memory consumption 
mincount <- 1
keep <- rowSums(counts(DESeq.ds)) > mincount
table(keep)
## keep
## FALSE  TRUE 
## 17384 20051
DESeq.ds <- DESeq.ds[keep,]

Another alternative way to prefilter data is

# at least 3 samples with a count of 10 or higher
keep <- rowSums(counts(DESeq.ds) >= 10) >= 3

4.3 Normalize counts

Counts normalized using DESeq2’s median of ratios (size factor):

#calculate and normalize with DESeq's size factor
colSums(counts(DESeq.ds))
##   lane1   lane2   lane3   lane4   lane5   lane6   lane8 
##  978373 1156647 1441831 1485288 1823140 1834030  681596
DESeq.ds <- estimateSizeFactors(DESeq.ds)
sizeFactors(DESeq.ds)
##     lane1     lane2     lane3     lane4     lane5     lane6     lane8 
## 0.7912131 0.9433354 1.1884939 1.2307145 1.4099376 1.4224762 0.5141056
colData(DESeq.ds)
## DataFrame with 7 rows and 2 columns
##       condition sizeFactor
##        <factor>  <numeric>
## lane1      mock   0.791213
## lane2      mock   0.943335
## lane3      mock   1.188494
## lane4      mock   1.230714
## lane5      dht    1.409938
## lane6      dht    1.422476
## lane8      dht    0.514106
counts.sf_normalized <- counts(DESeq.ds, normalized = TRUE)

#put two plots in the same plotting space
par(mfrow=c(1, 2))
#plot DESeq's library size normalized counts
boxplot(counts.sf_normalized, notch = TRUE, main = "untransformed read counts", ylab = "read counts")
#plot log2 transformed DESeq's normalized counts
log.norm.counts <- log2(counts.sf_normalized + 1)
boxplot(log.norm.counts, notch = TRUE, main = "log2 - transformed read counts", ylab = "log2(read counts)")

DESeq2’s rlog() function returns values that are both normalized for sequencing depth and transformed to the log2 scale where the values are adjusted to fit the experiment-wide trend of the variance-mean relationship

#Transformation of read counts including variance shrinkage
DESeq.rlog <- rlog(DESeq.ds, blind = TRUE )
rlog.norm.counts <- assay(DESeq.rlog)

par(mfrow=c(2, 2))
#plot raw counts
plot(counts(DESeq.ds)[,1:2], cex =.1 , main = "Raw read counts" )
#plot DESeq's library size normalized counts
plot(counts.sf_normalized[,1:2], cex =.1 , main = "library size normalized read counts" )
#plot log2 transformed DESeq's library size normalized counts
plot(log.norm.counts[,1:2], cex =.1 , main = "library size normalized log2 (read counts)")
#plot rlog-transformed counts
plot(rlog.norm.counts[,1:2], cex =.1, main = "rlog-transformed read counts")

#mean-sd-plots based on all samples of the experiment
msd_plot <- meanSdPlot(log.norm.counts, ranks=FALSE, plot=FALSE)
msd_plot$gg + ggtitle("library size normalized log2 (read counts)") + ylab (" standard deviation") + ylim(0,1)

msd_plot <- meanSdPlot(rlog.norm.counts, ranks=FALSE, plot=FALSE)
msd_plot$gg + ggtitle("rlog-transformed read counts") + ylab ("standard deviation") + ylim(0,1)

Question: Visually explore the normalized and transformed read counts between sample 1 and 2? Describe the differences between (1) raw read counts, (2) DESeq’s library size normalized counts, (3) log2 transformed DESeq’s library size normalized counts, and (4) DESeq’s rlog-transformed counts.
Click for answer The different normalization and transformation steps make the read counts between samples more comparable.
Question: Many statistical tests and analyses assume that data is homoskedastic, i.e. that all variables have similar variance. However, data with large differences among the sizes of the individual observations often shows heteroskedastic behavior. Do you see a dependence of the standard deviation (or variance) on the mean for (1) log2 transformed DESeq’s library size normalized counts, and (2) DESeq’s rlog-transformed counts?
Click for answer The dependence of the variance on the mean in the log transformed counts violate the assumption of homoskedasticity. The transformation of read counts including variance shrinkage with DESeq2’s rlog() function has removed this dependency (the standard deviation is roughly constant along the whole dynamic range).

4.4 Exploring global read count patterns

4.4.1 Hierarchical clustering

For hierarchical clustering of samples you have to decide about a similarity measure for pairwise comparison of individual samples and a linkage measure to define clusters. For background, see: https://chagall.med.cornell.edu/RNASEQcourse/Intro2RNAseq.pdf#subsubsection.5.3.2

distance.m_rlog <- as.dist(1-cor(rlog.norm.counts, method="pearson"))
plot(hclust(distance.m_rlog), labels = colnames(rlog.norm.counts), main="rlog transformed read counts\ndistance: Pearson correlation")

Question: Can you make a dendrogram with Euclidean distance and linkage method “average”?
Click for answer Run as.dist and hclust with the appropriate parameter settings. To find them check the help pages, e.g. by typing “?as.dist”.

4.4.2 Dimension reduction: PCA (Principal component analysis)

##                        PC1          PC2          PC3
## ENSG00000151503 0.13874907 -0.016138996 -0.004162831
## ENSG00000127954 0.13141463 -0.016883064 -0.002963539
## ENSG00000096060 0.12255415 -0.007604871 -0.020581968
## ENSG00000166451 0.11158962  0.023341492  0.002558022
## ENSG00000131016 0.10664453  0.030888580 -0.008942789
## ENSG00000166086 0.09734326  0.012337766  0.052912923

Question: How well can the different conditions be separated through dimension reduction? How much of the variance is described by the principle component that separates conditions?
Click for answer The first principle component separates the two conditions and explains 93% of the variance in the data (which is unusual high for RNA-seq data!)
Question: How did we select the genes used for principle component analysis? How do the results change with a different subset of genes? Do the overall conclusions change?
Click for answer We selected the 500 Highly Variable Genes (HVGs) with the largest variance of rlog transformed counts. Different numbers of selected HVGs result in the same overall conclusion that the two conditions are very much explained by PC 1 - however, less variance is explained by PC 1 with larger numbers of selected HVGs.
Question: What is the interpretation of genes with the largest positive and the largest negative loadings for PC1?
Click for answer The genes with largest positive loadings have the highest fold change in treated samples compared to mock, and genes with largest negative loadings have the highest fold change in mock samples compared to dht.

4.5 Differential expression

First we set the reference condition (depending on how you specify the contrast for the DGE analysis this step might be skipped):

# Setup the factor levels for design 
str(colData(DESeq.ds)$condition)
##  Factor w/ 2 levels "dht","mock": 2 2 2 2 1 1 1
# We set "mock" as the first level which will be treated as reference condition in the differential expression analysis
colData(DESeq.ds)$condition <- relevel(colData(DESeq.ds)$condition, "mock")
str(colData(DESeq.ds)$condition)
##  Factor w/ 2 levels "mock","dht": 1 1 1 1 2 2 2

4.5.1 Design matrix with intercept

# Defining design formula
design(DESeq.ds) <- ~ condition

# Run DESeq
DESeq.ds <- DESeq(DESeq.ds)
## using pre-existing size factors
## estimating dispersions
## gene-wise dispersion estimates
## mean-dispersion relationship
## final dispersion estimates
## fitting model and testing
#instead of calling the function DESeq you can also run the following sequence of commands:
#DESeq.ds <- estimateSizeFactors(DESeq.ds)
#DESeq.ds <- estimateDispersions(DESeq.ds)
#DESeq.ds <- nbinomWaldTest(DESeq.ds)

# Differential expression results 
# We are comparing "dht" vs "mock" in column 'condition'
# The contrast is specified by contrast = c("condition", "dht", "mock").
# Alternative the same contrast can be specified by c(0,1) if "mock" is set as reference condition in the design
DGE.results <- results(object = DESeq.ds, 
                       independentFiltering = TRUE, 
                       alpha = 0.05, 
                       contrast = c("condition", "dht", "mock")
                       )
summary(DGE.results)
## 
## out of 20051 with nonzero total read count
## adjusted p-value < 0.05
## LFC > 0 (up)       : 1667, 8.3%
## LFC < 0 (down)     : 1472, 7.3%
## outliers [1]       : 0, 0%
## low counts [2]     : 6998, 35%
## (mean count < 4)
## [1] see 'cooksCutoff' argument of ?results
## [2] see 'independentFiltering' argument of ?results
Question: How many differentially expressed genes are found with multiple testing adjusted p<0.05?
Click for answer 1667 differentially expressed genes with LFC > 0 (up in dht); and 1472 differentially expressed genes with LFC < 0 (down in dht).

4.5.2 Design matrix without intercept

# Defining design formula
design(DESeq.ds) <- ~0 + condition

# Run DESeq
DESeq.ds <- DESeq(DESeq.ds)
## using pre-existing size factors
## estimating dispersions
## found already estimated dispersions, replacing these
## gene-wise dispersion estimates
## mean-dispersion relationship
## final dispersion estimates
## fitting model and testing
# Differential expression results 
# We are comparing "dht" vs "mock" in column 'condition'
# The contrast is specified by contrast = c("condition", "dht", "mock").
# Alternative the same contrast can be specified by c(-1,1)
DGE.results <- results(object = DESeq.ds, 
                       independentFiltering = TRUE, 
                       alpha = 0.05, 
                       contrast = c("condition", "dht", "mock")
                       )
summary(DGE.results)
## 
## out of 20051 with nonzero total read count
## adjusted p-value < 0.05
## LFC > 0 (up)       : 1667, 8.3%
## LFC < 0 (down)     : 1472, 7.3%
## outliers [1]       : 0, 0%
## low counts [2]     : 6998, 35%
## (mean count < 4)
## [1] see 'cooksCutoff' argument of ?results
## [2] see 'independentFiltering' argument of ?results
Question: How many differentially expressed genes are found with multiple testing adjusted p<0.05?
Click for answer We get exactly the same results as using the design matrix with intercept.

Did you notice that adjusted p-values (column: padj) contain some NA values? If not, let’s have a look:

print(DGE.results)
## log2 fold change (MLE): condition dht vs mock 
## Wald test p-value: condition dht vs mock 
## DataFrame with 20051 rows and 6 columns
##                   baseMean log2FoldChange     lfcSE       stat     pvalue
##                  <numeric>      <numeric> <numeric>  <numeric>  <numeric>
## ENSG00000124208  529.42726      -0.455516  0.139864   -3.25685 0.00112657
## ENSG00000182463   31.22314       0.674510  0.338751    1.99116 0.04646281
## ENSG00000124201  225.12803      -0.081639  0.156691   -0.52102 0.60235271
## ENSG00000124205    1.18138      -3.532209  2.480126   -1.42421 0.15438711
## ENSG00000124207   73.83547      -0.443039  0.223947   -1.97832 0.04789224
## ...                    ...            ...       ...        ...        ...
## ENSG00000218917   0.221522      0.2609326  3.816151  0.0683759  0.9454864
## ENSG00000216800   2.573302      0.0589801  1.099924  0.0536220  0.9572363
## ENSG00000218597   7.596611     -0.7611229  0.676045 -1.1258465  0.2602305
## ENSG00000217348  17.902153      0.1084222  0.472040  0.2296887  0.8183336
## ENSG00000183878 137.611822      0.4820681  0.204801  2.3538410  0.0185806
##                      padj
##                 <numeric>
## ENSG00000124208 0.0069429
## ENSG00000182463 0.1440226
## ENSG00000124201 0.7807855
## ENSG00000124205        NA
## ENSG00000124207 0.1474728
## ...                   ...
## ENSG00000218917        NA
## ENSG00000216800        NA
## ENSG00000218597 0.4741469
## ENSG00000217348 0.9130644
## ENSG00000183878 0.0706473

This is because DESeq2 sets adjusted p-values to NA if those genes have low counts.

Question: How many genes have low counts?
Click for answer 6998 genes have low count.

Therefore, the genes with NA adjusted p-values are not of interest for us and we can remove them before proceeding with dowstream analysis.

DGE.results <- DGE.results[!is.na(DGE.results$padj),]

4.6 Visualization of DGE results

4.6.1 p-value histogram

The p-values follow a uniform distribution under null hypothesis. If you have a peak around zero, your alternative hypotheses live- along with some potential false positives.

If you would like to learn more about potential scenarious about how your p-value distribution might look like, here is a detailed blog post by David Robinson about “How to interpret a p-value histogram”.

# Histogram of p-values for all genes tested for no differential expression between the two conditions
hist(DGE.results$pvalue, col = "grey" , border = "white", xlab = "", ylab = "", main = "frequencies of p-values")

4.6.2 MA-plots

# MA plot
DESeq2::plotMA(DGE.results, alpha = 0.05, main = "Control vs. DHT-Treated" , ylim = c(-9,9))

4.6.3 Heatmaps

# Heatmap
DGE.results.sorted <- DGE.results[order(DGE.results$padj), ]
DGEgenes <- rownames(subset(DGE.results.sorted, padj < 0.05))
hm.mat_DGEgenes <- log.norm.counts[DGEgenes,]
# No clustering and no row (gene) scaling
aheatmap(hm.mat_DGEgenes, Rowv = NA, Colv = NA, main = "No clustering")

# Clustering and no row (gene) scaling.
aheatmap(hm.mat_DGEgenes, Rowv = TRUE, Colv = TRUE, distfun = "euclidean", hclustfun = "average", main = "Clustering without row (gene) scaling")

# Clustering and row (gene) scaling.
aheatmap(hm.mat_DGEgenes, Rowv = TRUE, Colv = TRUE, distfun = "euclidean", hclustfun = "average", scale = "row", main = "Clustering with row (gene) scaling")

# Gene scaling before hierarchical clustering.
aheatmap(t(scale(t(hm.mat_DGEgenes))), Rowv = TRUE, Colv = TRUE, distfun = "euclidean", hclustfun = "average", main = "Clustering after row (gene) scaling, and without sample-wise clustering")

4.6.4 Volcano plots

volDat <- as.data.frame(DGE.results.sorted)
volDat <- volDat[!is.na(volDat$padj), ]
volDat$DGE <- volDat$padj < 0.05

ggplot(volDat, aes(x = log2FoldChange, y = -log10(padj), color = DGE)) + 
  geom_point(alpha = 0.50) +
  scale_color_manual(values=c("TRUE"="red", "FALSE" = "gray"))

4.7 Annotating DGE results

## Create gene annotation

## Useful functions commented out below
#keytypes(org.Hs.eg.db)
#columns(org.Hs.eg.db)
anno <- AnnotationDbi::select(x = org.Hs.eg.db, 
                              keys = rownames(DGE.results), 
                              keytype = "ENSEMBL", 
                              columns = c("GENENAME", "SYMBOL"))
## 'select()' returned 1:many mapping between keys and columns
anno <- anno %>% 
  dplyr::group_by(ENSEMBL) %>% 
  dplyr::filter(n() == 1)

## merge DGE analysis results with gene annotation
deseq_dge <- merge(x = as.data.frame(DGE.results),
                   y = anno, 
                   by.x = "row.names", 
                   by.y = "ENSEMBL", 
                   all.x = TRUE,
                   all.y = FALSE)
colnames(deseq_dge)[1] <- "ENSEMBL"
deseq_dge <- deseq_dge %>% mutate(Direction = if_else(log2FoldChange >= 0, true = "up", false = "down"))
deseq_dge <- deseq_dge %>% dplyr::arrange(pvalue)
head(deseq_dge)
##           ENSEMBL  baseMean log2FoldChange      lfcSE     stat        pvalue
## 1 ENSG00000096060 1229.6845       4.983036 0.10241801 48.65390  0.000000e+00
## 2 ENSG00000115648 3541.8337       2.577111 0.06051060 42.58941  0.000000e+00
## 3 ENSG00000151503 1044.9213       5.797469 0.12824154 45.20742  0.000000e+00
## 4 ENSG00000162772 1065.7118       3.294150 0.08743437 37.67569 1.242542e-310
## 5 ENSG00000166451  574.4599       4.665524 0.14183136 32.89487 2.602286e-237
## 6 ENSG00000064042 3383.6565       1.642962 0.04997638 32.87476 5.044265e-237
##            padj                                GENENAME SYMBOL Direction
## 1  0.000000e+00                 FKBP prolyl isomerase 5  FKBP5        up
## 2  0.000000e+00                            melanophilin   MLPH        up
## 3  0.000000e+00 non-SMC condensin II complex subunit D3 NCAPD3        up
## 4 4.054725e-307       activating transcription factor 3   ATF3        up
## 5 6.793527e-234                    centromere protein N  CENPN        up
## 6 1.097380e-233     LIM and calponin homology domains 1 LIMCH1        up
## Create output
# all results 
write.table(deseq_dge, 
            file = "DESeq2_all-genes.txt", 
            sep = "\t", 
            quote = FALSE, 
            row.names = FALSE)

# only differentially expressed genes 
write.table(deseq_dge %>% dplyr::filter(padj < 0.05), 
            file = "DESeq2_de-genes.txt", 
            sep = "\t", 
            quote = FALSE, 
            row.names = FALSE)


## Plot individual genes
deseq_dge %>% dplyr::filter(SYMBOL=="TMEFF2") #known differential expressed gene in LNCaP human prostate cancer progression model
##           ENSEMBL baseMean log2FoldChange     lfcSE      stat       pvalue
## 1 ENSG00000144339 209.3953      -1.021127 0.1544868 -6.609806 3.848242e-11
##           padj
## 1 9.319315e-10
##                                                                 GENENAME SYMBOL
## 1 transmembrane protein with EGF like and two follistatin like domains 2 TMEFF2
##   Direction
## 1      down
plotCounts(dds = DESeq.ds, intgroup = c("condition"),
           gene = "ENSG00000144339", 
           normalized = TRUE, 
           transform = FALSE, 
           main = expression(atop("Expression of "*italic("TMEFF2"))))

Question: What is the function of TMEFF2? Does the expression profile of the gene fit with your expectations?
Click for answer Would love to hear your interpretation personally :) For instance check the following publication: https://www.nature.com/articles/1205142