Open In Colab

Analysis of RNA-seq data using R

getwd()

'/content'

list.files()

'sample_data'

# Define base URL and files to download
base_url <- "https://raw.githubusercontent.com/Bix4UMD/BIOI611_lab/refs/heads/main/data/bulkRNA_SE_tab/"
files <- c("N2_day1_rep1.ReadsPerGene.out.tab",
           "N2_day1_rep2.ReadsPerGene.out.tab",
           "N2_day1_rep3.ReadsPerGene.out.tab",
           "N2_day7_rep1.ReadsPerGene.out.tab",
           "N2_day7_rep2.ReadsPerGene.out.tab",
           "N2_day7_rep3.ReadsPerGene.out.tab"
           )

# Download each file
for (f in files) {
  download.file(paste0(base_url, f), destfile = f, method = "libcurl")
}
list.files()
  1. 'N2_day1_rep1.ReadsPerGene.out.tab'
  2. 'N2_day1_rep2.ReadsPerGene.out.tab'
  3. 'N2_day1_rep3.ReadsPerGene.out.tab'
  4. 'N2_day7_rep1.ReadsPerGene.out.tab'
  5. 'N2_day7_rep2.ReadsPerGene.out.tab'
  6. 'N2_day7_rep3.ReadsPerGene.out.tab'
  7. 'sample_data'
file_paths <- list.files(pattern = "*.ReadsPerGene.out.tab")
file_paths
  1. 'N2_day1_rep1.ReadsPerGene.out.tab'
  2. 'N2_day1_rep2.ReadsPerGene.out.tab'
  3. 'N2_day1_rep3.ReadsPerGene.out.tab'
  4. 'N2_day7_rep1.ReadsPerGene.out.tab'
  5. 'N2_day7_rep2.ReadsPerGene.out.tab'
  6. 'N2_day7_rep3.ReadsPerGene.out.tab'
# Function to read the STAR ReadsPerGene.out.tab file
read_star_file <- function(file_path) {
  # Read the file
  df <- read.table(file_path, header = FALSE, stringsAsFactors = FALSE)

  # Keep only the first (gene) and second (unstranded counts) columns
  library(dplyr)
  df <- df %>% select(V1, V2)

  # Rename the columns for clarity (GeneID and counts for this sample)
  colnames(df) <- c("GeneID", gsub(".ReadsPerGene.out.tab", "", basename(file_path)))

  return(df)
}

# Read all files into a list of data frames
list_of_dfs <- lapply(file_paths, read_star_file)

# Merge all data frames by the GeneID column
merged_df <- Reduce(function(x, y) merge(x, y, by = "GeneID"), list_of_dfs)

merged_df <- merged_df[-c(1:4), ]

# Check the first few rows of the combined data frame
head(merged_df)

# Optionally, write the combined data frame to a CSV file
write.csv(merged_df, "combined_gene_counts.csv", row.names = FALSE)
Attaching package: ‘dplyr’


The following objects are masked from ‘package:stats’:

    filter, lag


The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union
A data.frame: 6 × 7
GeneIDN2_day1_rep1N2_day1_rep2N2_day1_rep3N2_day7_rep1N2_day7_rep2N2_day7_rep3
<chr><int><int><int><int><int><int>
5WBGene00000001322721682589565926195239
6WBGene00000002 270 203 266 355 191 425
7WBGene00000003 341 415 411 387 255 499
8WBGene00000004 584 438 5181028 541 888
9WBGene00000005 383 395 483 119 65 189
10WBGene00000006 343 344 334 206 114 220
class(list_of_dfs)

'list'

head(list_of_dfs[[2]])
A data.frame: 6 × 2
GeneIDN2_day1_rep2
<chr><int>
1N_unmapped 1400596
2N_multimapping1305129
3N_noFeature 152183
4N_ambiguous 439830
5WBGene00000003 415
6WBGene00000007 513

rownames(merged_df) = merged_df$GeneID

head(merged_df)
A data.frame: 6 × 7
GeneIDN2_day1_rep1N2_day1_rep2N2_day1_rep3N2_day7_rep1N2_day7_rep2N2_day7_rep3
<chr><int><int><int><int><int><int>
WBGene00000001WBGene00000001322721682589565926195239
WBGene00000002WBGene00000002 270 203 266 355 191 425
WBGene00000003WBGene00000003 341 415 411 387 255 499
WBGene00000004WBGene00000004 584 438 5181028 541 888
WBGene00000005WBGene00000005 383 395 483 119 65 189
WBGene00000006WBGene00000006 343 344 334 206 114 220
# NULL reserved word representing empty
merged_df$GeneID = NULL
head(merged_df)
A data.frame: 6 × 6
N2_day1_rep1N2_day1_rep2N2_day1_rep3N2_day7_rep1N2_day7_rep2N2_day7_rep3
<int><int><int><int><int><int>
WBGene00000001322721682589565926195239
WBGene00000002 270 203 266 355 191 425
WBGene00000003 341 415 411 387 255 499
WBGene00000004 584 438 5181028 541 888
WBGene00000005 383 395 483 119 65 189
WBGene00000006 343 344 334 206 114 220
subset_df4test <- merged_df[, c("N2_day1_rep1", "N2_day1_rep2", "N2_day1_rep3")]
head(subset_df4test)
A data.frame: 6 × 3
N2_day1_rep1N2_day1_rep2N2_day1_rep3
<int><int><int>
WBGene00000001322721682589
WBGene00000002 270 203 266
WBGene00000003 341 415 411
WBGene00000004 584 438 518
WBGene00000005 383 395 483
WBGene00000006 343 344 334

Check count matrix

Different samples have different total number of counts

as.data.frame(colSums(merged_df))
A data.frame: 6 × 1
colSums(merged_df)
<dbl>
N2_day1_rep137398898
N2_day1_rep229488709
N2_day1_rep334593136
N2_day7_rep148275683
N2_day7_rep223204449
N2_day7_rep346005617
barplot(colSums(merged_df),
         las = 2,
         cex.names= 0.6)

png

# inkscape: an open source software for editing the graph saved in pdf
pdf("total_count_barplot.pdf")
barplot(colSums(merged_df),
         las = 2,
         cex.names= 0.6)
dev.off()

agg_record_e7152575705: 2

coldata <- colnames(merged_df)
coldata_df <- cbind(group = gsub("_rep\\d", "", coldata))
coldata_df
A matrix: 6 × 1 of type chr
group
N2_day1
N2_day1
N2_day1
N2_day7
N2_day7
N2_day7
rownames(coldata_df) = coldata
coldata_df
A matrix: 6 × 1 of type chr
group
N2_day1_rep1N2_day1
N2_day1_rep2N2_day1
N2_day1_rep3N2_day1
N2_day7_rep1N2_day7
N2_day7_rep2N2_day7
N2_day7_rep3N2_day7

Instsall required R packages

# if (!require("BiocManager", quietly = TRUE))
#     install.packages("BiocManager")
# if (!require("DESeq2", quietly = TRUE))
#     BiocManager::install("DESeq2")
# if (!requireNamespace("remotes", quietly = TRUE))
#     install.packages("remotes")
# if (!requireNamespace("EnhancedVolcano", quietly = TRUE))
#     remotes::install_github("kevinblighe/EnhancedVolcano")
## Installing the R packages could take around 10 minutes
## To speed up this process, you can download the R lib files
## saved from a working Google Colab session
## https://drive.google.com/file/d/1P9ESYYmDD9Y1HHB5mgxBRCWry2V49MJY/view?usp=sharing
system("gdown 1P9ESYYmDD9Y1HHB5mgxBRCWry2V49MJY", intern = TRUE)
system("md5sum R_lib_DESeq2.tar.gz", intern = TRUE)

'bd2af2cd2126342c4756ee3d75dd3911 R_lib_DESeq2.tar.gz'

## required by scater package
system("apt-get install libx11-dev libcairo2-dev", intern = TRUE)
system("tar zxvf R_lib_DESeq2.tar.gz")
  1. 'Reading package lists...'
  2. 'Building dependency tree...'
  3. 'Reading state information...'
  4. 'libx11-dev is already the newest version (2:1.8.7-1ubuntu0.1).'
  5. 'libx11-dev set to manually installed.'
  6. 'libcairo2-dev is already the newest version (1.18.0-3build1).'
  7. '0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.'
.libPaths(c("/content/usr/local/lib/R/site-library", .libPaths()))
.libPaths()
  1. '/content/usr/local/lib/R/site-library'
  2. '/usr/local/lib/R/site-library'
  3. '/usr/lib/R/site-library'
  4. '/usr/lib/R/library'

Load R packages

library(DESeq2)
library(EnhancedVolcano)
Loading required package: S4Vectors

Loading required package: stats4

Loading required package: BiocGenerics

Loading required package: generics


Attaching package: ‘generics’


The following object is masked from ‘package:dplyr’:

    explain


The following objects are masked from ‘package:base’:

    as.difftime, as.factor, as.ordered, intersect, is.element, setdiff,
    setequal, union



Attaching package: ‘BiocGenerics’


The following object is masked from ‘package:dplyr’:

    combine


The following objects are masked from ‘package:stats’:

    IQR, mad, sd, var, xtabs


The following objects are masked from ‘package:base’:

    anyDuplicated, aperm, append, as.data.frame, basename, cbind,
    colnames, dirname, do.call, duplicated, eval, evalq, Filter, Find,
    get, grep, grepl, is.unsorted, lapply, Map, mapply, match, mget,
    order, paste, pmax, pmax.int, pmin, pmin.int, Position, rank,
    rbind, Reduce, rownames, sapply, saveRDS, table, tapply, unique,
    unsplit, which.max, which.min



Attaching package: ‘S4Vectors’


The following objects are masked from ‘package:dplyr’:

    first, rename


The following object is masked from ‘package:utils’:

    findMatches


The following objects are masked from ‘package:base’:

    expand.grid, I, unname


Loading required package: IRanges


Attaching package: ‘IRanges’


The following objects are masked from ‘package:dplyr’:

    collapse, desc, slice


Loading required package: GenomicRanges

Loading required package: Seqinfo

Loading required package: SummarizedExperiment

Loading required package: MatrixGenerics

Loading required package: matrixStats


Attaching package: ‘matrixStats’


The following object is masked from ‘package:dplyr’:

    count



Attaching package: ‘MatrixGenerics’


The following objects are masked from ‘package:matrixStats’:

    colAlls, colAnyNAs, colAnys, colAvgsPerRowSet, colCollapse,
    colCounts, colCummaxs, colCummins, colCumprods, colCumsums,
    colDiffs, colIQRDiffs, colIQRs, colLogSumExps, colMadDiffs,
    colMads, colMaxs, colMeans2, colMedians, colMins, colOrderStats,
    colProds, colQuantiles, colRanges, colRanks, colSdDiffs, colSds,
    colSums2, colTabulates, colVarDiffs, colVars, colWeightedMads,
    colWeightedMeans, colWeightedMedians, colWeightedSds,
    colWeightedVars, rowAlls, rowAnyNAs, rowAnys, rowAvgsPerColSet,
    rowCollapse, rowCounts, rowCummaxs, rowCummins, rowCumprods,
    rowCumsums, rowDiffs, rowIQRDiffs, rowIQRs, rowLogSumExps,
    rowMadDiffs, rowMads, rowMaxs, rowMeans2, rowMedians, rowMins,
    rowOrderStats, rowProds, rowQuantiles, rowRanges, rowRanks,
    rowSdDiffs, rowSds, rowSums2, rowTabulates, rowVarDiffs, rowVars,
    rowWeightedMads, rowWeightedMeans, rowWeightedMedians,
    rowWeightedSds, rowWeightedVars


Loading required package: Biobase

Welcome to Bioconductor

    Vignettes contain introductory material; view with
    'browseVignettes()'. To cite Bioconductor, see
    'citation("Biobase")', and for packages 'citation("pkgname")'.



Attaching package: ‘Biobase’


The following object is masked from ‘package:MatrixGenerics’:

    rowMedians


The following objects are masked from ‘package:matrixStats’:

    anyMissing, rowMedians

Run DESeq2 to identify DEG

dds <- DESeqDataSetFromMatrix(countData = merged_df,
                              colData = coldata_df,
                              design =~ group)
class(dds)

The DESeq() function normalizes the read counts,estimates dispersions, and fits the linear model, all in one go.

dds <- DESeq(dds)

Dispersion is a measure of spread or variability in the data. Variance, standard deviation, IQR, among other measures, can all be used to measure dispersion.

DESeq2 uses a specific measure of dispersion (α) related to the mean (μ) and variance of the data: Var = μ + α*μ^2.

sizeFactors(dds)
head(counts(dds,  normalized = TRUE))

The function plotDispEsts shows the dispersion by mean of normalized counts. We expect the dispersion to decrease as the mean of normalized counts increases.

The functions shows:

  1. black per-gene dispersion estimates

  2. a red trend line representing the global relationship between dispersion and normalized count

  3. blue 'shrunken' values moderating individual dispersion estimates by the global relationship

  4. blue-circled dispersion outliers with high gene-wise dispersion that were not adjusted.

plotDispEsts(dds)

Plot normalized genes

The function plotCounts is used to plot normalized counts plus a pseudocount of 0.5 by default.

vsd <- vst(dds, blind=FALSE)
class(vsd)
plotPCA(vsd, intgroup = c("group"))

Extract DEG results using results function

res <- results(dds)
res
class(res)
mcols(res)$description
  • baseMean: mean of normalized counts for all samples
  • log2FoldChange: log2 fold change
  • lfcSE: standard error
  • stat: Wald statistic
  • pvalue: Wald test p-value
  • padj: BH adjusted p-values

If we used the p-value directly from the Wald test with a significance cut-off of p < 0.05, that means there is a 5% chance it is a false positives. Each p-value is the result of a single test (single gene). The more genes we test, the more we inflate the false positive rate. This is the multiple testing problem. For example, if we test 20,000 genes for differential expression, at p < 0.05 we would expect to find 1,000 genes by chance. If we found 3000 genes to be differentially expressed total, roughly one third of our genes are false positives. We would not want to sift through our “significant” genes to identify which ones are true positives.

DESeq2 helps reduce the number of genes tested by removing those genes unlikely to be significantly DE prior to testing, such as those with low number of counts and outlier samples (gene-level QC). However, we still need to correct for multiple testing to reduce the number of false positives, and there are a few common approaches:

  1. Bonferroni: The adjusted p-value is calculated by: p-value * m (m = total number of tests). This is a very conservative approach with a high probability of false negatives, so is generally not recommended.

  2. FDR/Benjamini-Hochberg: Benjamini and Hochberg (1995) defined the concept of FDR and created an algorithm to control the expected FDR below a specified level given a list of independent p-values. An interpretation of the BH method for controlling the FDR is implemented in DESeq2 in which we rank the genes by p-value, then multiply each ranked p-value by m/rank.

  3. Q-value / Storey method: The minimum FDR that can be attained when calling that feature significant. For example, if gene X has a q-value of 0.013 it means that 1.3% of genes that show p-values at least as small as gene X are false positives In DESeq2, the p-values attained by the Wald test are corrected for multiple testing using the Benjamini and Hochberg method by default. There are options to use other methods in the results() function. The p-adjusted values should be used to determine significant genes. The significant genes can be output for visualization and/or functional analysis.

So what does FDR < 0.05 mean? By setting the FDR cutoff to < 0.05, we’re saying that the proportion of false positives we expect amongst our differentially expressed genes is 5%. For example, if you call 500 genes as differentially expressed with an FDR cutoff of 0.05, you expect 25 of them to be false positives.

Note on p-values set to NA: some values in the results table can be set to NA for one of the following reasons:

  1. If within a row, all samples have zero counts, the baseMean column will be zero, and the log2 fold change estimates, p value and adjusted p value will all be set to NA.

  2. If a row contains a sample with an extreme count outlier then the p value and adjusted p value will be set to NA. These outlier counts are detected by Cook’s distance. Customization of this outlier filtering and description of functionality for replacement of outlier counts and refitting is described below

  3. If a row is filtered by automatic independent filtering, for having a low mean normalized count, then only the adjusted p value will be set to NA. Description and customization of independent filtering is described below

plotMA(res, ylim=c(-2,2))

write.csv(res, file = "BIOI_bulkRNAseq_SE_DESeq2_res.csv")
d <- plotCounts(dds, gene=which.min(res$padj), intgroup="group",
                returnData=TRUE)
d
which.min(res$padj)
library("ggplot2")
ggplot(d, aes(x=group, y=count)) +
  geom_point(position=position_jitter(w=0.1,h=0)) +
  scale_y_log10(breaks=c(25,100,400))
  EnhancedVolcano(res,
    lab = rownames(res),
    x = 'log2FoldChange',
    y = 'pvalue')

Understand normalized count in DESeq2 (Optional)

Create a pseudo-reference sample (row-wise geometric mean)

The code below creates a new column called pseudo_reference that contains the average log-transformed expression value for each gene across all samples. This pseudo-reference is similar to calculating a "reference sample" to compare other samples.

log_data = log(merged_df)
head(log_data)
library(dplyr)
library(tibble) # rownames_to_column

log_data = log_data %>%
             rownames_to_column('gene') %>%
             mutate (pseudo_reference = rowMeans(log_data))

head(log_data)
table(log_data$pseudo_reference == "-Inf")
filtered_log_data = log_data %>% filter(pseudo_reference != "-Inf")
head(filtered_log_data)
filtered_log_data$pseudo_reference = exp(filtered_log_data$pseudo_reference)
head(filtered_log_data)
dim(log_data)
dim(filtered_log_data)

Calculate ratio between each sample and the pseudo-reference for each gene

This step calculates the fold change between each sample and the pseudo-reference for each gene.

ratio_data = sweep(exp(filtered_log_data[,2:7]), 1, filtered_log_data[,8], "/")
head(ratio_data)

Calculate scaling factor

The code below computes the median fold change for each sample across all genes.


scaling_factors = apply(ratio_data, 2, median, na.rm = TRUE)
scaling_factors

The 2 indicates that the function is applied to columns, i.e., for each sample.

Normalize the counts

This step below normalizes each sample by its scaling factors, making the data comparable across samples. The result is a normalized gene expression matrix.

manually_normalized = sweep(merged_df, 2, scaling_factors, "/")
head(manually_normalized)
hist(manually_normalized$N2_day1_rep1)

The code below shows that the size factors and the normalized read counts calculated by ourselves are the same as what DESeq2 function returns.

head(counts(dds,  normalized = TRUE))

sizeFactors(dds)

SessionInfo

sessionInfo()