Barry Grant < http://thegrantlab.org/bimm143/ >
2020-05-24 (17:12:56 on Sun, May 24)
The data for this hands-on session comes from a published RNA-seq experiment where airway smooth muscle cells were treated with dexamethasone, a synthetic glucocorticoid steroid with anti-inflammatory effects (Himes et al. 2014).
Glucocorticoids are used, for example, by people with asthma to reduce inflammation of the airways. The anti-inflammatory effects on airway smooth muscle (ASM) cells has been known for some time but the underlying molecular mechanisms are unclear.
Himes et al. used RNA-seq to profile gene expression changes in four different ASM cell lines treated with dexamethasone glucocorticoid. They found a number of differentially expressed genes comparing dexamethasone-treated to control cells, but focus much of the discussion on a gene called CRISPLD2. This gene encodes a secreted protein known to be involved in lung development, and SNPs in this gene in previous GWAS studies are associated with inhaled corticosteroid resistance and bronchodilator response in asthma patients. They confirmed the upregulated CRISPLD2 mRNA expression with qPCR and increased protein expression using Western blotting.
In the experiment, four primary human ASM cell lines were treated with 1 micromolar dexamethasone for 18 hours. For each of the four cell lines, we have a treated and an untreated sample. They did their analysis using Tophat and Cufflinks similar to our last day’s hands-on session. For a more detailed description of their analysis see the PubMed entry 24926665 and for raw data see the GEO entry GSE52778.
In this session we will read and explore the gene expression data from this experiment using base R functions and then perform a detailed analysis with the DESeq2 package from Bioconductor.
As we already noted back in Week 6 Bioconductor is a large repository and resource for R packages that focus on analysis of high-throughput genomic data.
Bioconductor packages are installed differently than “regular”" R packages from CRAN. To install the core Bioconductor packages, copy and paste the following two lines of code into your R console one at a time.
N.B. Remember not to put these install commands in your Rmd report as it will at best re-install the packages every time you kint your report, which is not what you want, and at worst cause a confusing knit error.
If this finished without yielding obvious error messages we can install the DESeq2 bioconductor package that we will use in this class:
The entire install process can take some time as there are many packages with dependencies on other packages. For some important notes on the install process please see our Bioconductor setup notes. Your install process may produce some notes or other output. Generally, as long as you don’t get an error message, you’re good to move on. If you do see error messages then again please see our Bioconductor setup notes for debugging steps.
Finally, check that you have installed everything correctly by closing and reopening RStudio and entering the following two commands at the console window:
If you get a message that says something like: Error in library(DESeq2) : there is no package called 'DESeq2'
, then the required packages did not install correctly. Please see our Bioconductor setup notes and let us know so we can debug this together.
The computational analysis of an RNA-seq experiment begins from the FASTQ files that contain the nucleotide sequence of each read and a quality score at each position. These reads must first be aligned to a reference genome or transcriptome. The output of this alignment step is commonly stored in a file format called SAM/BAM. This is the workflow we followed last day.
Once the reads have been aligned, there are a number of tools that can be used to count the number of reads/fragments that can be assigned to genomic features for each sample. These often take as input SAM/BAM alignment files and a file specifying the genomic features, e.g. a GFF3 or GTF file specifying the gene models as obtained from ENSEMBLE or UCSC.
In the workflow we’ll use here, the abundance of each transcript was quantified using kallisto (software, paper) and transcript-level abundance estimates were then summarized to the gene level to produce length-scaled counts using the R package txImport (software, paper), suitable for using in count-based analysis tools like DESeq. This is the starting point - a “count matrix”, where each cell indicates the number of reads mapping to a particular gene (in rows) for each sample (in columns). This is where we left off last day when analyzing our 1000 genome data.
Note: This is one of several well-established workflows for data pre-processing. The goal here is to provide a reference point to acquire fundamental skills with DESeq2 that will be applicable to other bioinformatics tools and workflows. In this regard, the following resources summarize a number of best practices for RNA-seq data analysis and pre-processing.
- Conesa, A. et al. “A survey of best practices for RNA-seq data analysis.” Genome Biology 17:13 (2016).
- Soneson, C., Love, M. I. & Robinson, M. D. “Differential analyses for RNA-seq: transcript-level estimates improve gene-level inferences.” F1000Res. 4:1521 (2016).
- Griffith, Malachi, et al. “Informatics for RNA sequencing: a web resource for analysis on the cloud.” PLoS Comput Biol 11.8: e1004393 (2015).
As input, the DESeq2 package expects (1) a data.frame of count data (as obtained from RNA-seq or another high-throughput sequencing experiment) and (2) a second data.frame with information about the samples - often called sample metadata (or colData
in DESeq2-speak because it supplies metadata/information about the columns of the countData matrix).
The “count matrix” (called the countData
in DESeq2-speak) the value in the i-th row and the j-th column of the data.frame tells us how many reads can be assigned to gene i in sample j. Analogously, for other types of assays, the rows of this matrix might correspond e.g. to binding regions (with ChIP-Seq) or peptide sequences (with quantitative mass spectrometry).
For the sample metadata (i.e. colData
in DESeq2-speak) samples are in rows and metadata about those samples are in columns. Notice that the first column of colData must match the column names of countData (except the first, which is the gene ID column).
Note from the DESeq2 vignette: The values in the input contData object should be counts of sequencing reads/fragments. This is important for DESeq2’s statistical model to hold, as only counts allow assessing the measurement precision correctly. It is important to never provide counts that were pre-normalized for sequencing depth/library size, as the statistical model is most powerful when applied to un-normalized counts, and is designed to account for library size differences internally.
First, create a new RStudio project (File > New Project > New Directory > New Project) and download the input airway_scaledcounts.csv and airway_metadata.csv into your project directory.
Begin a new R script and use the read.csv() function to read these count data and metadata files.
counts <- read.csv("airway_scaledcounts.csv", stringsAsFactors = FALSE, row.names=1)
metadata <- read.csv("airway_metadata.csv", stringsAsFactors = FALSE)
Now, take a look at each.
You can also use the View() function to view the entire object. Notice something here. The sample IDs in the metadata sheet (SRR1039508, SRR1039509, etc.) exactly match the column names of the countdata, except for the first column, which contains the Ensembl gene ID. This is important, and we’ll get more strict about it later on.
The functions dim()
, nrow()
and View()
may be useful for answering these questions.
Lets perform some exploratory differential gene expression analysis. Note: this analysis is for demonstration only. NEVER do differential expression analysis this way!
Look at the metadata object again to see which samples are control
and which are drug treated
. You can also see this in the metadata printed table below:
Metadata for the Himes et al. RNASeq experiment | |||
---|---|---|---|
Note the 'dex' column specifies drug presence/absence | |||
id | dex | celltype | geo_id |
SRR1039508 | control | N61311 | GSM1275862 |
SRR1039509 | treated | N61311 | GSM1275863 |
SRR1039512 | control | N052611 | GSM1275866 |
SRR1039513 | treated | N052611 | GSM1275867 |
SRR1039516 | control | N080611 | GSM1275870 |
SRR1039517 | treated | N080611 | GSM1275871 |
SRR1039520 | control | N061011 | GSM1275874 |
SRR1039521 | treated | N061011 | GSM1275875 |
Note that the control samples are SRR1039508, SRR1039512, SRR1039516, and SRR1039520. This bit of code will first find the sample id
for those labeled control. Then calculate the mean counts per gene across these samples:
control <- metadata[metadata[,"dex"]=="control",]
control.counts <- counts[ ,control$id]
control.mean <- rowSums( control.counts )/4
head(control.mean)
## ENSG00000000003 ENSG00000000005 ENSG00000000419 ENSG00000000457 ENSG00000000460
## 900.75 0.00 520.50 339.75 97.25
## ENSG00000000938
## 0.75
Side-note: An alternative way to do this same thing using the dplyr
package from the tidyverse is shown below. Which do you prefer and why?
library(dplyr)
control <- metadata %>% filter(dex=="control")
control.counts <- counts %>% select(control$id)
control.mean <- rowSums(control.counts)/4
head(control.mean)
## ENSG00000000003 ENSG00000000005 ENSG00000000419 ENSG00000000457 ENSG00000000460
## 900.75 0.00 520.50 339.75 97.25
## ENSG00000000938
## 0.75
treated
samples (i.e. calculate the mean per gene across drug treated samples and assign to a labeled vector called treated.mean
)For Q3 consider what would happen if you were to add more samples. Would the values obtained with the exact code above be correct?
For Q4 you can adapt the above code being sure to substitute "treated"
for "control"
. For example:
We will combine our meancount data for bookkeeping purposes.
Directly comparing the raw counts is going to be problematic if we just happened to sequence one group at a higher depth than another. Later on we’ll do this analysis properly, normalizing by sequencing depth per sample using a better approach. But for now, colSums() the data to show the sum of the mean counts across all genes for each group. Your answer should look like this:
## control.mean treated.mean
## 23005324 22196524
Wait a sec. There are 60,000-some rows in this data, but I’m only seeing a few dozen dots at most outside of the big clump around the origin.
See the help for ?plot.default to see how to set log axis.
We can find candidate differentially expressed genes by looking for genes with a large change between control and dex-treated samples. We usually look at the log2 of the fold change, because this has better mathematical properties.
Here we calculate log2foldchange, add it to our meancounts
data.frame and inspect the results either with the head() or the View() function for example.
There are a couple of “weird” results. Namely, the NaN (“not a number”) and -Inf (negative infinity) results.
The NaN is returned when you divide by zero and try to take the log. The -Inf is returned when you try to take the log of zero. It turns out that there are a lot of genes with zero expression. Let’s filter our data to remove these genes. Again inspect your result (and the intermediate steps) to see if things make sense to you
zero.vals <- which(meancounts[,1:2]==0, arr.ind=TRUE)
to.rm <- unique(zero.vals[,1])
mycounts <- meancounts[-to.rm,]
head(mycounts)
arr.ind
argument in the which() function call above? Why would we then take the first column of the output and need to call the unique() function?The arr.ind=TRUE
argument will clause which() to return both the row and column indices (i.e. positions) where there are TRUE values. In this case this will tell us which genes (rows) and samples (columns) have zero counts. We are going to ignore any genes that have zero counts in any sample so we just focus on the row
answer. Calling unique() will ensure we dont count any row twice if it has zer entries in both samples. Ask Barry to discuss and demo this further;-)
A common threshold used for calling something differentially expressed is a log2(FoldChange) of greater than 2 or less than -2. Let’s filter the dataset both ways to see how many genes are up or down-regulated.
Q8. Using the up.ind
vector above can you determine how many up regulated genes we have at the greater than 2 fc level?
Q9. Using the down.ind
vector above can you determine how many down regulated genes we have at the greater than 2 fc level?
Q10. Do you trust these results? Why or why not?
What type of vectors are up.ind
and down.ind
? How could you count the number of TRUE elements? Your answers should look like:
## [1] "Up: 250"
## [1] "Down: 367"
For question 10, all our analysis has been done based on fold change. However, fold change can be large (e.g. >>two-fold up- or down-regulation) without being statistically significant (e.g. based on p-values). We have not done anything yet to determine whether the differences we are seeing are significant. These results in their current form are likely to be very misleading. In the next section we will begin to do this properly with the help of the DESeq2 package.
In total, you should of reported 617 differentially expressed genes, in either direction.
Let’s do this the right way. DESeq2 is an R package specifically for analyzing count-based NGS data like RNA-seq. It is available from Bioconductor. Bioconductor is a project to provide tools for analyzing high-throughput genomic data including RNA-seq, ChIP-seq and arrays. You can explore Bioconductor packages here.
Bioconductor packages usually have great documentation in the form of vignettes. For a great example, take a look at the DESeq2 vignette for analyzing count data. This 40+ page manual is packed full of examples on using DESeq2, importing data, fitting models, creating visualizations, references, etc.
Just like R packages from CRAN, you only need to install Bioconductor packages once (instructions here), then load them every time you start a new R session.
Take a second and read through all the stuff that flies by the screen when you load the DESeq2 package. When you first installed DESeq2 it may have taken a while, because DESeq2 depends on a number of other R packages (S4Vectors, BiocGenerics, parallel, IRanges, etc.) Each of these, in turn, may depend on other packages. These are all loaded into your working environment when you load DESeq2. Also notice the lines that start with The following objects are masked from 'package:...
.
Bioconductor software packages often define and use custom class objects for storing data. This helps to ensure that all the needed data for analysis (and the results) are available. DESeq works on a particular type of object called a DESeqDataSet. The DESeqDataSet is a single object that contains input values, intermediate calculations like how things are normalized, and all results of a differential expression analysis.
You can construct a DESeqDataSet from (1) a count matrix, (2) a metadata file, and (3) a formula indicating the design of the experiment.
We have talked about (1) and (2) previously. The third needed item that has to be specified at the beginning of the analysis is a design formula. This tells DESeq2 which columns in the sample information table (colData
) specify the experimental design (i.e. which groups the samples belong to) and how these factors should be used in the analysis. Essentially, this formula expresses how the counts for each gene depend on the variables in colData.
Take a look at metadata
again. The thing we’re interested in is the dex
column, which tells us which samples are treated with dexamethasone versus which samples are untreated controls. We’ll specify the design with a tilde, like this: design=~dex
. (The tilde is the shifted key to the left of the number 1 key on my keyboard. It looks like a little squiggly line).
We will use the DESeqDataSetFromMatrix() function to build the required DESeqDataSet object and call it dds
, short for our DESeqDataSet. If you get a warning about “some variables in design formula are characters, converting to factors” don’t worry about it. Take a look at the dds
object once you create it.
## class: DESeqDataSet
## dim: 38694 8
## metadata(1): version
## assays(1): counts
## rownames(38694): ENSG00000000003 ENSG00000000005 ... ENSG00000283120
## ENSG00000283123
## rowData names(0):
## colnames(8): SRR1039508 SRR1039509 ... SRR1039520 SRR1039521
## colData names(4): id dex celltype geo_id
Next, let’s run the DESeq analysis pipeline on the dataset, and reassign the resulting object back to the same variable. Note that before we start, dds
is a bare-bones DESeqDataSet. The DESeq()
function takes a DESeqDataSet and returns a DESeqDataSet, but with additional information filled in (including the differential expression results we are after). Notice how if we try to access these results before running the analysis, nothing exists.
## Error in results(dds): couldn't find results. you should first run DESeq()
Here, we’re running the DESeq pipeline on the dds
object, and reassigning the whole thing back to dds
, which will now be a DESeqDataSet populated with all those values. Get some help on ?DESeq
(notice, no “2” on the end). This function calls a number of other functions within the package to essentially run the entire pipeline (normalizing by library size by estimating the “size factors,” estimating dispersion for the negative binomial model, and fitting models and getting statistics for each gene for the design specified when you imported the data).
## estimating size factors
## estimating dispersions
## gene-wise dispersion estimates
## mean-dispersion relationship
## final dispersion estimates
## fitting model and testing
Since we’ve got a fairly simple design (single factor, two groups, treated versus control), we can get results out of the object simply by calling the results()
function on the DESeqDataSet that has been run through the pipeline. The help page for ?results
and the vignette both have extensive documentation about how to pull out the results for more complicated models (multi-factor experiments, specific contrasts, interaction terms, time courses, etc.).
## log2 fold change (MLE): dex treated vs control
## Wald test p-value: dex treated vs control
## DataFrame with 38694 rows and 6 columns
## baseMean log2FoldChange lfcSE
## <numeric> <numeric> <numeric>
## ENSG00000000003 747.194195359907 -0.350703020686579 0.168245681332529
## ENSG00000000005 0 NA NA
## ENSG00000000419 520.134160051965 0.206107766417861 0.101059218008052
## ENSG00000000457 322.664843927049 0.0245269479387471 0.145145067649248
## ENSG00000000460 87.682625164828 -0.14714204922212 0.257007253994673
## ... ... ... ...
## ENSG00000283115 0 NA NA
## ENSG00000283116 0 NA NA
## ENSG00000283119 0 NA NA
## ENSG00000283120 0.974916032393564 -0.66825846051647 1.69456285241871
## ENSG00000283123 0 NA NA
## stat pvalue padj
## <numeric> <numeric> <numeric>
## ENSG00000000003 -2.0844696749953 0.0371174658432827 0.163034808641681
## ENSG00000000005 NA NA NA
## ENSG00000000419 2.0394751758463 0.0414026263001167 0.176031664879168
## ENSG00000000457 0.168982303952746 0.865810560623561 0.961694238404388
## ENSG00000000460 -0.57252099672319 0.566969065257939 0.815848587637724
## ... ... ... ...
## ENSG00000283115 NA NA NA
## ENSG00000283116 NA NA NA
## ENSG00000283119 NA NA NA
## ENSG00000283120 -0.394354484734893 0.693319342566817 NA
## ENSG00000283123 NA NA NA
Convert the res
object to a data.frame with the as.data.frame()
function and then pass it to View()
to bring it up in a data viewer.
Why do you think so many of the adjusted p-values are missing (NA
)? Try looking at the baseMean
column, which tells you the average overall expression of this gene, and how that relates to whether or not the p-value was missing. Go to the DESeq2 vignette and read the section about “Independent filtering and multiple testing.”
Note. The goal of independent filtering is to filter out those tests from the procedure that have no, or little chance of showing significant evidence, without even looking at the statistical result. Genes with very low counts are not likely to see significant differences typically due to high dispersion. This results in increased detection power at the same experiment-wide type I error [i.e., better FDRs].
We can summarize some basic tallies using the summary function.
##
## out of 25258 with nonzero total read count
## adjusted p-value < 0.1
## LFC > 0 (up) : 1563, 6.2%
## LFC < 0 (down) : 1188, 4.7%
## outliers [1] : 142, 0.56%
## low counts [2] : 9971, 39%
## (mean count < 10)
## [1] see 'cooksCutoff' argument of ?results
## [2] see 'independentFiltering' argument of ?results
The results function contains a number of arguments to customize the results table. By default the argument alpha
is set to 0.1. If the adjusted p value cutoff will be a value other than 0.1, alpha should be set to that value:
##
## out of 25258 with nonzero total read count
## adjusted p-value < 0.05
## LFC > 0 (up) : 1236, 4.9%
## LFC < 0 (down) : 933, 3.7%
## outliers [1] : 142, 0.56%
## low counts [2] : 9033, 36%
## (mean count < 6)
## [1] see 'cooksCutoff' argument of ?results
## [2] see 'independentFiltering' argument of ?results
Our result table so far only contains the Ensembl gene IDs. However, alternative gene names and extra annotation are usually required for informative interpretation of our results. In this section we will add this necessary annotation data to our results.
We will use one of Bioconductor’s main annotation packages to help with mapping between various ID schemes. Here we load the AnnotationDbi package and the annotation data package for humans org.Hs.eg.db.
Note: You may have to install these with the
BiocManager::install("AnnotationDbi")
andBiocManager::install("org.Hs.eg.db")
function calls.
The later of these is is the organism annotation package (“org”) for Homo sapiens (“Hs”), organized as an AnnotationDbi database package (“db”), using Entrez Gene IDs (“eg”) as primary key. To get a list of all available key types that we can use to map between, use the columns()
function:
## [1] "ACCNUM" "ALIAS" "ENSEMBL" "ENSEMBLPROT" "ENSEMBLTRANS"
## [6] "ENTREZID" "ENZYME" "EVIDENCE" "EVIDENCEALL" "GENENAME"
## [11] "GO" "GOALL" "IPI" "MAP" "OMIM"
## [16] "ONTOLOGY" "ONTOLOGYALL" "PATH" "PFAM" "PMID"
## [21] "PROSITE" "REFSEQ" "SYMBOL" "UCSCKG" "UNIGENE"
## [26] "UNIPROT"
Side-note: You can also pull up documentation (i.e. help) with a description of these different values with the regular help()
command, e.g. help("REFSEQ")
The main function we will use from the AnnotationDbi package is called mapIds().
We can use the mapIds() function to add individual columns to our results table. We provide the row names of our results table as a key, and specify that keytype=ENSEMBL
. The column
argument tells the mapIds() function which information we want, and the multiVals
argument tells the function what to do if there are multiple possible values for a single input value. Here we ask to just give us back the first one that occurs in the database.
res$symbol <- mapIds(org.Hs.eg.db,
keys=row.names(res), # Our genenames
keytype="ENSEMBL", # The format of our genenames
column="SYMBOL", # The new format we want to add
multiVals="first")
## log2 fold change (MLE): dex treated vs control
## Wald test p-value: dex treated vs control
## DataFrame with 6 rows and 7 columns
## baseMean log2FoldChange lfcSE
## <numeric> <numeric> <numeric>
## ENSG00000000003 747.194195359907 -0.350703020686579 0.168245681332529
## ENSG00000000005 0 NA NA
## ENSG00000000419 520.134160051965 0.206107766417861 0.101059218008052
## ENSG00000000457 322.664843927049 0.0245269479387471 0.145145067649248
## ENSG00000000460 87.682625164828 -0.14714204922212 0.257007253994673
## ENSG00000000938 0.319166568913118 -1.73228897394308 3.49360097648095
## stat pvalue padj
## <numeric> <numeric> <numeric>
## ENSG00000000003 -2.0844696749953 0.0371174658432827 0.163034808641681
## ENSG00000000005 NA NA NA
## ENSG00000000419 2.0394751758463 0.0414026263001167 0.176031664879168
## ENSG00000000457 0.168982303952746 0.865810560623561 0.961694238404388
## ENSG00000000460 -0.57252099672319 0.566969065257939 0.815848587637724
## ENSG00000000938 -0.495846258804286 0.620002884826012 NA
## symbol
## <character>
## ENSG00000000003 TSPAN6
## ENSG00000000005 TNMD
## ENSG00000000419 DPM1
## ENSG00000000457 SCYL3
## ENSG00000000460 C1orf112
## ENSG00000000938 FGR
res$entrez
, res$uniprot
and res$genename
.Your code and results should look like the following:
res$entrez <- mapIds(org.Hs.eg.db,
keys=row.names(res),
column="ENTREZID",
keytype="ENSEMBL",
multiVals="first")
res$uniprot <- mapIds(org.Hs.eg.db,
keys=row.names(res),
column="UNIPROT",
keytype="ENSEMBL",
multiVals="first")
res$genename <- mapIds(org.Hs.eg.db,
keys=row.names(res),
column="GENENAME",
keytype="ENSEMBL",
multiVals="first")
head(res)
## log2 fold change (MLE): dex treated vs control
## Wald test p-value: dex treated vs control
## DataFrame with 6 rows and 10 columns
## baseMean log2FoldChange lfcSE
## <numeric> <numeric> <numeric>
## ENSG00000000003 747.194195359907 -0.350703020686579 0.168245681332529
## ENSG00000000005 0 NA NA
## ENSG00000000419 520.134160051965 0.206107766417861 0.101059218008052
## ENSG00000000457 322.664843927049 0.0245269479387471 0.145145067649248
## ENSG00000000460 87.682625164828 -0.14714204922212 0.257007253994673
## ENSG00000000938 0.319166568913118 -1.73228897394308 3.49360097648095
## stat pvalue padj
## <numeric> <numeric> <numeric>
## ENSG00000000003 -2.0844696749953 0.0371174658432827 0.163034808641681
## ENSG00000000005 NA NA NA
## ENSG00000000419 2.0394751758463 0.0414026263001167 0.176031664879168
## ENSG00000000457 0.168982303952746 0.865810560623561 0.961694238404388
## ENSG00000000460 -0.57252099672319 0.566969065257939 0.815848587637724
## ENSG00000000938 -0.495846258804286 0.620002884826012 NA
## symbol entrez uniprot
## <character> <character> <character>
## ENSG00000000003 TSPAN6 7105 A0A024RCI0
## ENSG00000000005 TNMD 64102 Q9H2S6
## ENSG00000000419 DPM1 8813 O60762
## ENSG00000000457 SCYL3 57147 Q8IZE3
## ENSG00000000460 C1orf112 55732 A0A024R922
## ENSG00000000938 FGR 2268 P09769
## genename
## <character>
## ENSG00000000003 tetraspanin 6
## ENSG00000000005 tenomodulin
## ENSG00000000419 dolichyl-phosphate mannosyltransferase subunit 1, catalytic
## ENSG00000000457 SCY1 like pseudokinase 3
## ENSG00000000460 chromosome 1 open reading frame 112
## ENSG00000000938 FGR proto-oncogene, Src family tyrosine kinase
You can arrange and view the results by the adjusted p-value
## log2 fold change (MLE): dex treated vs control
## Wald test p-value: dex treated vs control
## DataFrame with 6 rows and 10 columns
## baseMean log2FoldChange lfcSE
## <numeric> <numeric> <numeric>
## ENSG00000152583 954.770931565544 4.36835864527065 0.237126791796018
## ENSG00000179094 743.252688449073 2.86388865850472 0.175569314419061
## ENSG00000116584 2277.91345410747 -1.03470077244439 0.065098436086062
## ENSG00000189221 2383.75370672631 3.34154402446201 0.212405785251703
## ENSG00000120129 3440.70375496308 2.9652108028191 0.203695128555544
## ENSG00000148175 13493.9203682606 1.42716828092125 0.100389041282998
## stat pvalue padj
## <numeric> <numeric> <numeric>
## ENSG00000152583 18.4220374770153 8.74489804217429e-76 1.3244148084873e-71
## ENSG00000179094 16.3120114012008 8.1078355641998e-60 6.1396584809903e-56
## ENSG00000116584 -15.8944029173986 6.92854593249887e-57 3.49776093825651e-53
## ENSG00000189221 15.7318880015545 9.14432590230387e-56 3.4622703947598e-52
## ENSG00000120129 14.5571021940789 5.26424315691443e-48 1.59453925222938e-44
## ENSG00000148175 14.2163752405806 7.25127847390255e-46 1.83034354145423e-42
## symbol entrez uniprot
## <character> <character> <character>
## ENSG00000152583 SPARCL1 8404 A0A024RDE1
## ENSG00000179094 PER1 5187 O15534
## ENSG00000116584 ARHGEF2 9181 Q92974
## ENSG00000189221 MAOA 4128 P21397
## ENSG00000120129 DUSP1 1843 B4DU40
## ENSG00000148175 STOM 2040 F8VSL7
## genename
## <character>
## ENSG00000152583 SPARC like 1
## ENSG00000179094 period circadian regulator 1
## ENSG00000116584 Rho/Rac guanine nucleotide exchange factor 2
## ENSG00000189221 monoamine oxidase A
## ENSG00000120129 dual specificity phosphatase 1
## ENSG00000148175 stomatin
Finally, let’s write out the ordered significant results with annotations. See the help for ?write.csv if you are unsure here.
Let’s make a commonly produced visualization from this data, namely a so-called Volcano plot. These summary figures are frequently used to highlight the proportion of genes that are both significantly regulated and display a high fold change.
Typically these plots shows the log fold change on the X-axis, and the \(-log_{10}\) of the p-value on the Y-axis (the more significant the p-value, the larger the \(-log_{10}\) of that value will be). A very dull (i.e. non colored and labeled) version can be created with a quick call to plot() like so:
To make this more useful we can add some guidelines (with the abline()
function) and color (with a custom color vector) highlighting genes that have padj<0.05 and the absolute log2FoldChange>2.
plot( res$log2FoldChange, -log(res$padj),
ylab="-Log(P-value)", xlab="Log2(FoldChange)")
# Add some cut-off lines
abline(v=c(-2,2), col="darkgray", lty=2)
abline(h=-log(0.05), col="darkgray", lty=2)
To color the points we will setup a custom color vector indicating transcripts with large fold change and significant differences between conditions:
# Setup our custom point color vector
mycols <- rep("gray", nrow(res))
mycols[ abs(res$log2FoldChange) > 2 ] <- "red"
inds <- (res$padj < 0.01) & (abs(res$log2FoldChange) > 2 )
mycols[ inds ] <- "blue"
# Volcano plot with custom colors
plot( res$log2FoldChange, -log(res$padj),
col=mycols, ylab="-Log(P-value)", xlab="Log2(FoldChange)" )
# Cut-off lines
abline(v=c(-2,2), col="gray", lty=2)
abline(h=-log(0.1), col="gray", lty=2)
For even more customization you might find the EnhancedVolcano bioconductor package useful (Note. It uses ggplot under the hood):
First we will add the more understandable gene symbol names to our full results object res
as we will use this to label the most interesting genes in our final plot.
In the final section below we will find out how to derive biological (and hopefully) mechanistic insight from the subset of our most interesting genes highlighted in these types of plots.
Pathway analysis (also known as gene set analysis or over-representation analysis), aims to reduce the complexity of interpreting gene lists via mapping the listed genes to known (i.e. annotated) biological pathways, processes and functions.
Side-note: Pathway analysis can actually mean many different things to different people. This includes analysis of Gene Ontology (GO) terms, protein–protein interaction networks, flux-balance analysis from kinetic simulations of pathways, etc. However, pathway analysis most commonly focuses on methods that exploit existing pathway knowledge (e.g. in public repositories such as GO or KEGG), rather than on methods that infer pathways from molecular measurements. These more general approaches are nicely reviewed in this paper:
- Khatri, et al. “Ten years of pathway analysis: current approaches and outstanding challenges.” PLoS Comput Biol 8.2 (2012): e1002375.
There are many freely available tools for pathway or over-representation analysis. Ath the time of writting Bioconductor alone has over 80 packages categorized under gene set enrichment and over 120 packages categorized under pathways.
Here we play with just one, the GAGE package (which stands for Generally Applicable Gene set Enrichment), to do KEGG pathway enrichment analysis on our RNA-seq based differential expression results.
The KEGG pathway database, unlike GO for example, provides functional annotation as well as information about gene products that interact with each other in a given pathway, how they interact (e.g., activation, inhibition, etc.), and where they interact (e.g., cytoplasm, nucleus, etc.). Hence KEGG has the potential to provide extra insight beyond annotation lists of simple molecular function, process etc. from GO terms.
In this analysis, we check for coordinated differential expression over gene sets from KEGG pathways instead of changes of individual genes. The assumption here is that consistent perturbations over a given pathway (gene set) may suggest mechanistic changes.
Once we have a list of enriched pathways from gage we will use the pathview package to draw pathway diagrams, coloring the molecules in the pathway by their degree of up/down-regulation.
First we need to do our one time install of these required bioconductor packages:
# Run in your R console (i.e. not your Rmarkdown doc!)
BiocManager::install( c("pathview", "gage", "gageData") )
Now we can load the packages and setup the KEGG data-sets we need. The gageData package has pre-compiled databases mapping genes to KEGG pathways and GO terms for common organisms. kegg.sets.hs
is a named list of 229 elements. Each element is a character vector of member gene Entrez IDs for a single KEGG pathway.
library(pathview)
library(gage)
library(gageData)
data(kegg.sets.hs)
# Examine the first 2 pathways in this kegg set for humans
head(kegg.sets.hs, 2)
## $`hsa00232 Caffeine metabolism`
## [1] "10" "1544" "1548" "1549" "1553" "7498" "9"
##
## $`hsa00983 Drug metabolism - other enzymes`
## [1] "10" "1066" "10720" "10941" "151531" "1548" "1549" "1551"
## [9] "1553" "1576" "1577" "1806" "1807" "1890" "221223" "2990"
## [17] "3251" "3614" "3615" "3704" "51733" "54490" "54575" "54576"
## [25] "54577" "54578" "54579" "54600" "54657" "54658" "54659" "54963"
## [33] "574537" "64816" "7083" "7084" "7172" "7363" "7364" "7365"
## [41] "7366" "7367" "7371" "7372" "7378" "7498" "79799" "83549"
## [49] "8824" "8833" "9" "978"
The main gage() function requires a named vector of fold changes, where the names of the values are the Entrez gene IDs.
Note that we used the mapIDs() function above to obtain Entrez gene IDs (stored in res$entrez
) and we have the fold change results from DESeq2 analysis (stored in res$log2FoldChange
).
## 7105 64102 8813 57147 55732 2268
## -0.35070302 NA 0.20610777 0.02452695 -0.14714205 -1.73228897
Now, let’s run the gage pathway analysis.
See help on the gage function with ?gage
. Specifically, you might want to try changing the value of same.dir
. This value determines whether to test for changes in a gene set toward a single direction (all genes up or down regulated) or changes towards both directions simultaneously (i.e. any genes in the pathway dysregulated). Here, we’re using the default same.dir=TRUE
, which will give us separate lists for pathways that are upregulated versus pathways that are down-regulated.
Now lets look at the object returned from gage().
## $names
## [1] "greater" "less" "stats"
It is a list with three elements, “greater”, “less” and “stats”.
You can also see this in your Environmnet panel/tab window of RStudio or use the R command str(keggres)
.
Like any list we can use the dollar syntax to access a named element, e.g. head(keggres$greater)
and head(keggres$less)
.
Lets look at the first few down (less) pathway results:
## p.geomean stat.mean p.val
## hsa05332 Graft-versus-host disease 0.0004250461 -3.473346 0.0004250461
## hsa04940 Type I diabetes mellitus 0.0017820293 -3.002352 0.0017820293
## hsa05310 Asthma 0.0020045888 -3.009050 0.0020045888
## q.val set.size exp1
## hsa05332 Graft-versus-host disease 0.09053483 40 0.0004250461
## hsa04940 Type I diabetes mellitus 0.14232581 42 0.0017820293
## hsa05310 Asthma 0.14232581 29 0.0020045888
Each keggres$less
and keggres$greater
object is data matrix with gene sets as rows sorted by p-value.
The top three Kegg pathways indicated here include Graft-versus-host disease, Type I diabetes and the Asthma pathway (with pathway ID hsa05310).
Now, let’s try out the pathview() function from the pathview package to make a pathway plot with our RNA-Seq expression results shown in color.
To begin with lets manually supply a pathway.id
(namely the first part of the "hsa05310 Asthma"
) that we could see from the print out above.
This downloads the pathway figure data from KEGG and adds our results to it. Here is the default low resolution raster PNG output from the pathview() call above:
Note how many of the genes in this pathway are perturbed (i.e. colored) in our results.
You can play with the other input arguments to pathview() to change the display in various ways including generating a PDF graph. For example:
# A different PDF based output of the same data
pathview(gene.data=foldchanges, pathway.id="hsa05310", kegg.native=FALSE)
Q12. Can you do the same procedure as above to plot the pathview figures for the top 2 down-reguled pathways?
If you are interested in delving further into pathway analysis you are welcome to check out the optional additional lab session focusing on this topic where we utilize KEGG, GO and Reactome to analyze a different RNA-Seq experiment from start to finish.
DESeq2 offers a function called plotCounts()
that takes a DESeqDataSet that has been run through the pipeline, the name of a gene, and the name of the variable in the colData
that you’re interested in, and plots those values. See the help for ?plotCounts
. Let’s first see what the gene ID is for the CRISPLD2 gene using:
## log2 fold change (MLE): dex treated vs control
## Wald test p-value: dex treated vs control
## DataFrame with 1 row and 10 columns
## baseMean log2FoldChange lfcSE
## <numeric> <numeric> <numeric>
## ENSG00000103196 3096.15933899728 2.6260341339809 0.267444466152902
## stat pvalue padj
## <numeric> <numeric> <numeric>
## ENSG00000103196 9.81898848667731 9.32747411487363e-23 3.36344274928003e-20
## symbol entrez uniprot
## <character> <character> <character>
## ENSG00000103196 CRISPLD2 83716 A0A140VK80
## genename
## <character>
## ENSG00000103196 cysteine rich secretory protein LCCL domain containing 2
## [1] "ENSG00000103196"
Now, with that gene ID in hand let’s plot the counts, where our intgroup
, or “interesting group” variable is the “dex” column.
That’s just okay. Keep looking at the help for ?plotCounts
. Notice that we could have actually returned the data instead of plotting. We could then pipe this to ggplot and make our own figure. Let’s make a boxplot.
# Return the data
d <- plotCounts(dds, gene="ENSG00000103196", intgroup="dex", returnData=TRUE)
head(d)
We can mow use this returned object to plot a boxplot with the base graphics function boxplot()
As the returned object is a data.frame it is also all setup for ggplot2 based plotting. For example:
library(ggplot2)
ggplot(d, aes(dex, count, fill=dex)) +
geom_boxplot() +
scale_y_log10() +
ggtitle("CRISPLD2")
Which plot do you prefer? Maybe time to learn more about ggplot via the available DataCamp course ;-) Of course there are many other interesting genes that our results have highlighted and you could now explore these further using the same approach outlined above.
The sessionInfo()
prints version information about R and any attached packages. It’s a good practice to always run this command at the end of your R session and record it for the sake of reproducibility in the future.
## R version 3.6.0 (2019-04-26)
## Platform: x86_64-apple-darwin15.6.0 (64-bit)
## Running under: macOS High Sierra 10.13.6
##
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib
##
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
##
## attached base packages:
## [1] parallel stats4 stats graphics grDevices utils datasets
## [8] methods base
##
## other attached packages:
## [1] gageData_2.24.0 gage_2.36.0
## [3] pathview_1.26.0 EnhancedVolcano_1.4.0
## [5] ggrepel_0.8.1 ggplot2_3.3.0
## [7] org.Hs.eg.db_3.10.0 AnnotationDbi_1.48.0
## [9] dplyr_0.8.5 gt_0.2.0.5
## [11] DESeq2_1.26.0 SummarizedExperiment_1.16.1
## [13] DelayedArray_0.12.2 BiocParallel_1.20.1
## [15] matrixStats_0.55.0 Biobase_2.46.0
## [17] GenomicRanges_1.38.0 GenomeInfoDb_1.22.0
## [19] IRanges_2.20.2 S4Vectors_0.24.3
## [21] BiocGenerics_0.32.0 BiocManager_1.30.10
## [23] labsheet_0.1.2
##
## loaded via a namespace (and not attached):
## [1] bitops_1.0-6 bit64_0.9-7 httr_1.4.1
## [4] RColorBrewer_1.1-2 Rgraphviz_2.30.0 tools_3.6.0
## [7] backports_1.1.5 R6_2.4.1 rpart_4.1-15
## [10] Hmisc_4.3-1 DBI_1.1.0 colorspace_1.4-1
## [13] nnet_7.3-13 withr_2.1.2 tidyselect_1.1.0
## [16] gridExtra_2.3 bit_1.1-15.2 compiler_3.6.0
## [19] graph_1.64.0 htmlTable_1.13.3 labeling_0.3
## [22] sass_0.2.0 KEGGgraph_1.46.0 scales_1.1.0
## [25] checkmate_2.0.0 genefilter_1.68.0 webex_0.9.1
## [28] commonmark_1.7 stringr_1.4.0 digest_0.6.25
## [31] foreign_0.8-75 rmarkdown_2.1 XVector_0.26.0
## [34] base64enc_0.1-3 jpeg_0.1-8.1 pkgconfig_2.0.3
## [37] htmltools_0.4.0 htmlwidgets_1.5.1 rlang_0.4.6.9000
## [40] rstudioapi_0.11 RSQLite_2.2.0 farver_2.0.3
## [43] jsonlite_1.6.1 acepack_1.4.1 RCurl_1.98-1.1
## [46] magrittr_1.5 GenomeInfoDbData_1.2.2 Formula_1.2-3
## [49] Matrix_1.2-18 Rcpp_1.0.4 munsell_0.5.0
## [52] lifecycle_0.2.0 stringi_1.4.6 yaml_2.2.1
## [55] zlibbioc_1.32.0 grid_3.6.0 blob_1.2.1
## [58] crayon_1.3.4 lattice_0.20-40 Biostrings_2.54.0
## [61] splines_3.6.0 annotate_1.64.0 KEGGREST_1.26.1
## [64] locfit_1.5-9.1 knitr_1.28 pillar_1.4.4
## [67] geneplotter_1.64.0 XML_3.99-0.3 glue_1.4.1
## [70] evaluate_0.14 latticeExtra_0.6-29 data.table_1.12.8
## [73] png_0.1-7 vctrs_0.3.0 gtable_0.3.0
## [76] purrr_0.3.4 assertthat_0.2.1 xfun_0.12
## [79] xtable_1.8-4 survival_3.1-8 tibble_3.0.1
## [82] memoise_1.1.0 cluster_2.1.0 ellipsis_0.3.1