This exercise will show how to obtain clinical and genomic data from the Cancer Genome Atlas (TGCA) and to perform classical analysis important for clinical data.
These include:
First, we start by loading all libraries necessary for this exercise. Please check their documentation if you want to know more.
# Load packages
library("TCGAbiolinks")
## Warning: replacing previous import 'utils::findMatches' by
## 'S4Vectors::findMatches' when loading 'AnnotationDbi'
library("limma")
library("edgeR")
library("glmnet")
library("factoextra")
library("FactoMineR")
library("caret")
library("SummarizedExperiment")
library("gplots")
library("survival")
library("survminer")
library("RColorBrewer")
library("clusterProfiler")
library("genefilter")
In this tutorial, we will focus on Liver Hepatocellular Carcinoma, which is identified in TCGA as LIHC. For LIHC, TCGA provides data for 377 patients including: clinical, expression, DNA methylation and genotyping data. In this tutorial, we will work with clinical and expression data (RNA-seq). Go to https://portal.gdc.cancer.gov/ and search for TCGA-LIHC if you want to understand the data deposited in TCGA. You can also try to find your way through the previous data to look for other data sets of your interest.
We will make use of the TCGAbiolinks library, which allows us to query, prepare and download data from the TCGA portal. TCGAbiolinks provides important functionality as matching data of same the donors across distinct data types (clinical vs expression) and provides data structures to make its analysis in R easy.
To download TCGA data with TCGAbiolinks, you need to follow 3 steps. First, you will query the TCGA database through R with the function GDCquery. This will allow you to investigate the data available at the TCGA database. Next, we use GDCdownload to download raw version of desired files into your computer. Finally GDCprepare will read these files and make R data structures so that we can further analyse them.
Before we get there however we need to know what we are searching for. We can check all the available projects at TCGA with the command bellow. Since there are many lets look at the first 6 projects using the command head()
.
GDCprojects <- getGDCprojects()
head(GDCprojects[c("project_id", "name")])
## project_id name
## 1 TARGET-AML Acute Myeloid Leukemia
## 2 MATCH-Z1I Genomic Characterization CS-MATCH-0007 Arm Z1I
## 3 HCMI-CMDC NCI Cancer Model Development for the Human Cancer Model Initiative
## 4 MATCH-W Genomic Characterization CS-MATCH-0007 Arm W
## 5 MATCH-Z1D Genomic Characterization CS-MATCH-0007 Arm Z1D
## 6 MATCH-Z1A Genomic Characterization CS-MATCH-0007 Arm Z1A
As a general rule in R (and especially if you are working in RStudio) whenever some method returns some value or table you are not familiar with, you should check its structure and dimensions. You can always use functions such as head()
to only show the first entries and dim()
to check the dimension of the data.
We already know that Liver Hepatocellular Carcinoma has as id TCGA-LIHC. We can use the following function to get details on all data deposited for TCGA-LIHC.
TCGAbiolinks::getProjectSummary("TCGA-LIHC")
## $file_count
## [1] 20820
##
## $data_categories
## file_count case_count data_category
## 1 6070 377 Simple Nucleotide Variation
## 2 3226 377 Sequencing Reads
## 3 1634 377 Biospecimen
## 4 803 377 Clinical
## 5 4197 377 Copy Number Variation
## 6 1698 376 Transcriptome Profiling
## 7 1290 377 DNA Methylation
## 8 184 184 Proteome Profiling
## 9 22 11 Somatic Structural Variation
## 10 1696 371 Structural Variation
##
## $case_count
## [1] 377
##
## $file_size
## [1] 2.340194e+14
Of note, not all patients were measured for all data types. Also, some data types have more files than samples. This is the case when more experiments were performed per patient, i.e. transcriptome profiling was performed both in mRNA and miRNA, or that data have been analysed by distinct computational strategies.
Let us start by querying all RNA-seq data from LIHC project. When using GDCquery we always need to specify the id of the project, i.e. “TCGA_LIHC”, and the data category we are interested in, i.e. “Transcriptome Profiling”. Here, we will focus on a particular type of data summarization for mRNA-seq data (workflow.type), which is based on raw counts estimated with STAR (an alignment algorithm).
Note that performing this query will take a few minutes
query_TCGA <- GDCquery(
project = "TCGA-LIHC",
data.category = "Transcriptome Profiling", # parameter enforced by GDCquery
data.type = "Gene Expression Quantification",
experimental.strategy = "RNA-Seq",
workflow.type = "STAR - Counts"
)
To visualize the query results in a more readable way, we can use the command getResults.
lihc_res <- getResults(query_TCGA) # make results as table
# head(lihc_res) # data of the first 6 patients.
colnames(lihc_res) # columns present in the table
## [1] "id" "data_format"
## [3] "cases" "access"
## [5] "file_name" "submitter_id"
## [7] "data_category" "type"
## [9] "platform" "file_size"
## [11] "created_datetime" "md5sum"
## [13] "updated_datetime" "file_id"
## [15] "data_type" "state"
## [17] "experimental_strategy" "version"
## [19] "data_release" "project"
## [21] "analysis_id" "analysis_state"
## [23] "analysis_submitter_id" "analysis_workflow_link"
## [25] "analysis_workflow_type" "analysis_workflow_version"
## [27] "sample_type" "is_ffpe"
## [29] "cases.submitter_id" "sample.submitter_id"
One interesting question is the tissue type measured at an experiment (normal, solid tissue, cell line). This information is present at column sample_type
.
head(lihc_res$sample_type) # first 6 types of tissue.
## [1] "Primary Tumor" "Solid Tissue Normal" "Primary Tumor"
## [4] "Primary Tumor" "Primary Tumor" "Primary Tumor"
sample_type
is a categorical variable, which can be better visualized with the table function, so that we can check how many different categories exist in the data.
table(lihc_res$sample_type) # summary of distinct tissues types present in this study
##
## Primary Tumor Recurrent Tumor Solid Tissue Normal
## 371 3 50
As you see, there are 50 controls (Solid Tissue Normal) and 371 cancer samples (Primary Tumors). For simplicity, we will ignore the small class of recurrent tumors. Therefore, we will redo the query as
query_TCGA <- GDCquery(
project = "TCGA-LIHC",
data.category = "Transcriptome Profiling", # parameter enforced by GDCquery
data.type = "Gene Expression Quantification",
experimental.strategy = "RNA-Seq",
workflow.type = "STAR - Counts",
sample.type = c("Primary Tumor", "Solid Tissue Normal")
)
Next, we need to download the files from the query. Before, be sure that you set your current working directory to the place you want to save your data. TCGA will save the data in a directory structure starting with a directory “GDCdata”.
To avoid issues related to having everyone downloading lots of data at the same time, we will further subset our data query. If you wanted to just work with the whole dataset you would skip this next step. In fact this is the process we have done to generate the data that you will work with. Hopefully you have already downloaded the data. Here we will select just the first 3 tumor and 3 control samples.
lihc_res <- getResults(query_TCGA) # make results as table
keep_tumor <- which(lihc_res$sample_type == "Primary Tumor")[1:3]
keep_control <- which(lihc_res$sample_type == "Solid Tissue Normal")[1:3]
sample_barcodes <- lihc_res$sample.submitter_id[c(keep_tumor, keep_control)]
small_query_TCGA <- GDCquery(
project = "TCGA-LIHC",
data.category = "Transcriptome Profiling", # parameter enforced by GDCquery
data.type = "Gene Expression Quantification",
experimental.strategy = "RNA-Seq",
workflow.type = "STAR - Counts",
sample.type = c("Primary Tumor", "Solid Tissue Normal"),
barcode = sample_barcodes
)
Let us now download the files specified in the query. Note the directory parameter.
GDCdownload(query = small_query_TCGA, directory = "SMALL_GDCdata")
Given that you need to download many files, the previous operation might take some time. Often the download fails for one or another file. You can re-run the previous command (GDCdownload) until no error message is given. The method will recognize that the data has already been downloaded and won’t download the data again.
Finally, lets load the actual RNAseq data into R. Remember that the output directory set must be the same to where you have downloaded the data.
small_tcga_data <- GDCprepare(small_query_TCGA, directory = "SMALL_GDCdata")
We can then check the size of the object with the command.
dim(small_tcga_data)
## [1] 60660 6
We have done this just to quickly illustrate how to query and download the data directly using the TCGAbiolinks package. We will now work with the full dataset as queried in query_TCGA. We will skip the download step and just perform the GDCprepare step, this loads the data into R. Once again, note the directory parameter. The folder (GDCdata) that we have asked you to download should be in your working directory.
tcga_data <- GDCprepare(query_TCGA, directory = "GDCdata")
There are 3 functions that allow us to access to most important data present in this object, these are: colData()
, rowData()
, assays()
. Use the command ?SummarizedExperiment
to find more details. colData()
allows us to access the clinical data associated with our samples. The functions colnames()
and rownames()
can be used to extract the column and rows names from a given table respectively. But be careful if you have large objects. The colnames()
and rownames()
functions return all column and row names, even if you have tens of thousands. The combination header(colnames())
can make more sense in these cases.
# In R (and other programming languages) you can often
# chain functions to save time and space
colnames(colData(tcga_data))
## [1] "barcode" "patient"
## [3] "sample" "shortLetterCode"
## [5] "definition" "sample_submitter_id"
## [7] "sample_type_id" "tumor_descriptor"
## [9] "sample_id" "sample_type"
## [11] "composition" "days_to_collection"
## [13] "state" "initial_weight"
## [15] "preservation_method" "pathology_report_uuid"
## [17] "submitter_id" "oct_embedded"
## [19] "specimen_type" "is_ffpe"
## [21] "tissue_type" "synchronous_malignancy"
## [23] "ajcc_pathologic_stage" "days_to_diagnosis"
## [25] "treatments" "last_known_disease_status"
## [27] "tissue_or_organ_of_origin" "days_to_last_follow_up"
## [29] "age_at_diagnosis" "primary_diagnosis"
## [31] "prior_malignancy" "year_of_diagnosis"
## [33] "prior_treatment" "ajcc_staging_system_edition"
## [35] "ajcc_pathologic_t" "morphology"
## [37] "ajcc_pathologic_n" "ajcc_pathologic_m"
## [39] "classification_of_tumor" "diagnosis_id"
## [41] "icd_10_code" "site_of_resection_or_biopsy"
## [43] "tumor_grade" "progression_or_recurrence"
## [45] "alcohol_history" "exposure_id"
## [47] "race" "gender"
## [49] "ethnicity" "vital_status"
## [51] "age_at_index" "days_to_birth"
## [53] "year_of_birth" "demographic_id"
## [55] "days_to_death" "year_of_death"
## [57] "bcr_patient_barcode" "primary_site"
## [59] "project_id" "disease_type"
## [61] "name" "releasable"
## [63] "released" "sample.aux"
This link provides a basic explanation about tcga_data
. Note that both clinical and expression data are present in this object.
Lets look at some potentially interesting features. The table()
function (in this context) produces a small summary with the sum of each of the factors present in a given column.
table(tcga_data@colData$vital_status)
##
## Alive Dead Not Reported
## 255 164 2
table(tcga_data@colData$ajcc_pathologic_stage)
##
## Stage I Stage II Stage III Stage IIIA Stage IIIB Stage IIIC Stage IV
## 189 97 6 73 8 10 3
## Stage IVA Stage IVB
## 1 2
table(tcga_data@colData$definition)
##
## Primary solid Tumor Solid Tissue Normal
## 371 50
table(tcga_data@colData$tissue_or_organ_of_origin)
##
## Liver
## 421
table(tcga_data@colData$gender)
##
## female male
## 143 278
table(tcga_data@colData$race)
##
## american indian or alaska native asian
## 2 164
## black or african american not reported
## 24 13
## white
## 218
Is there a particular column (feature) that allows you to distinguish tumor tissue from normal tissue?
What about the RNA-seq data? We can use the assay
function to obtain the RNA-seq count matrices and rowData
to see gene mapping information. Can you tell how many genes and how many samples are included there?
dim(assay(tcga_data)) # gene expression matrices.
## [1] 60660 421
head(assay(tcga_data)[, 1:10]) # expression of first 6 genes and first 10 samples
## TCGA-FV-A3I0-01A-11R-A22L-07 TCGA-DD-A3A6-11A-11R-A22L-07
## ENSG00000000003.15 16693 2980
## ENSG00000000005.6 0 0
## ENSG00000000419.13 1419 405
## ENSG00000000457.14 543 130
## ENSG00000000460.17 132 26
## ENSG00000000938.13 188 24
## TCGA-DD-A3A6-01A-11R-A22L-07 TCGA-BD-A3ER-01A-11R-A213-07
## ENSG00000000003.15 783 3056
## ENSG00000000005.6 74 0
## ENSG00000000419.13 279 633
## ENSG00000000457.14 202 397
## ENSG00000000460.17 26 98
## ENSG00000000938.13 412 237
## TCGA-CC-5261-01A-01R-A131-07 TCGA-DD-AAVZ-01A-11R-A41C-07
## ENSG00000000003.15 4785 7408
## ENSG00000000005.6 0 0
## ENSG00000000419.13 1908 1010
## ENSG00000000457.14 975 885
## ENSG00000000460.17 451 279
## ENSG00000000938.13 326 105
## TCGA-DD-AADN-01A-11R-A41C-07 TCGA-DD-A1EB-01A-11R-A131-07
## ENSG00000000003.15 861 2595
## ENSG00000000005.6 1 5
## ENSG00000000419.13 310 1138
## ENSG00000000457.14 41 1039
## ENSG00000000460.17 9 86
## ENSG00000000938.13 660 146
## TCGA-LG-A9QD-01A-11R-A38B-07 TCGA-G3-A25T-01A-11R-A16W-07
## ENSG00000000003.15 4752 6110
## ENSG00000000005.6 12 0
## ENSG00000000419.13 1039 1548
## ENSG00000000457.14 547 398
## ENSG00000000460.17 95 90
## ENSG00000000938.13 129 239
head(rowData(tcga_data)) # ensembl id and gene id of the first 6 genes.
## DataFrame with 6 rows and 10 columns
## source type score phase gene_id
## <factor> <factor> <numeric> <integer> <character>
## ENSG00000000003.15 HAVANA gene NA NA ENSG00000000003.15
## ENSG00000000005.6 HAVANA gene NA NA ENSG00000000005.6
## ENSG00000000419.13 HAVANA gene NA NA ENSG00000000419.13
## ENSG00000000457.14 HAVANA gene NA NA ENSG00000000457.14
## ENSG00000000460.17 HAVANA gene NA NA ENSG00000000460.17
## ENSG00000000938.13 HAVANA gene NA NA ENSG00000000938.13
## gene_type gene_name level hgnc_id
## <character> <character> <character> <character>
## ENSG00000000003.15 protein_coding TSPAN6 2 HGNC:11858
## ENSG00000000005.6 protein_coding TNMD 2 HGNC:17757
## ENSG00000000419.13 protein_coding DPM1 2 HGNC:3005
## ENSG00000000457.14 protein_coding SCYL3 2 HGNC:19285
## ENSG00000000460.17 protein_coding C1orf112 2 HGNC:25565
## ENSG00000000938.13 protein_coding FGR 2 HGNC:3697
## havana_gene
## <character>
## ENSG00000000003.15 OTTHUMG00000022002.2
## ENSG00000000005.6 OTTHUMG00000022001.2
## ENSG00000000419.13 OTTHUMG00000032742.2
## ENSG00000000457.14 OTTHUMG00000035941.6
## ENSG00000000460.17 OTTHUMG00000035821.9
## ENSG00000000938.13 OTTHUMG00000003516.3
Finally, we can use some core functionality of R to save the TCGA_data as an .RDS file. This is faster than repeating the previous operations and useful if you need to work on your data for several days or at a later time.
# Save the data as a file, if you need it later, you can just load this file
# instead of having to run the whole pipeline again
saveRDS(
object = tcga_data,
file = "tcga_data.RDS",
compress = FALSE
)
The data can be loaded with the following command:
tcga_data <- readRDS(file = "tcga_data.RDS")
A typical task on RNA-Seq data is differential expression (DE) analysis, based on some clinical phenotypes. This, in turn, requires normalization of the data, as in its raw format it may have batch effects and other artifacts.
A common approach to such complex tasks is to define a computational pipeline
, performing several steps in sequence, allowing the user to select different parameters.
We will now define and run one such pipeline, through the use of an R function
.
The function is called limma_pipeline(tcga_data, condition_variable, reference_group)
, where tcga_data
is the data object we have gotten from TCGA and condition_variable
is the interesting variable/condition by which you want to group your patient samples. You can also decide which one of the values of your conditional variable is going to be the reference group, with the reference_group
parameter.
This function returns a list with three different objects:
voom
, this contains the TMM+voom normalized
data;eBayes
, this contains the the fitted model plus a number of statistics related to each of the probes;topTable
, which contains the top 100 differentially expressed genes sorted by p-value
. This is how the code of this function:limma_pipeline = function(
tcga_data,
condition_variable,
reference_group=NULL){
design_factor = colData(tcga_data)[, condition_variable, drop=T]
group = factor(design_factor)
if(!is.null(reference_group)){group = relevel(group, ref=reference_group)}
design = model.matrix(~ group)
dge = DGEList(counts=assay(tcga_data),
samples=colData(tcga_data),
genes=as.data.frame(rowData(tcga_data)))
# filtering
keep = filterByExpr(dge,design)
dge = dge[keep,,keep.lib.sizes=FALSE]
rm(keep)
# Normalization (TMM followed by voom)
dge = calcNormFactors(dge)
v = voom(dge, design, plot=TRUE)
# Fit model to data given design
fit = lmFit(v, design)
fit = eBayes(fit)
# Show top genes
topGenes = topTable(fit, coef=ncol(design), number=100, sort.by="p")
return(
list(
voomObj=v, # normalized data
fit=fit, # fitted model and statistics
topGenes=topGenes # the 100 most differentially expressed genes
)
)
}
Please read the Details
tab for a step by step explanation of what this pipeline does. For now, copy the limma_pipeline
function in your R console, so we can start using it on the TCGA data.
With the following command, we can obtain the DE analysis comparing Primary solid Tumor
samples against Solid Tissue Normal
. This will be used in the next section, on the classification task.
limma_res = limma_pipeline(
tcga_data = tcga_data,
condition_variable = "definition",
reference_group = "Solid Tissue Normal"
)
Let’s save this object to file, like we did with tcga_data
:
# Save the data as a file, if you need it later, you can just load this file
# instead of having to run the whole pipeline again
saveRDS(
object = limma_res,
file = "limma_res.RDS",
compress = FALSE
)
As an example, we also show here how we can use limma_pipeline
to perform DE analysis by grouping patients by gender instead of by tissue type.
gender_limma_res = limma_pipeline(
tcga_data = tcga_data,
condition_variable = "gender",
reference_group = "female"
)
In our pipeline function, we use the package limma
. We will select a particular clinical feature of the data to use as class for grouping the samples as either tumor vs normal tissue. This data is available under the column definition
for tcga_data
, but needs the use of the function colData
to be accessed. In addition, limma requires this data to be a factor
, so we convert it as such:
clinical_data = colData(tcga_data)
group = factor(clinical_data$definition)
As seen before, we have 2 distinct groups of tissues defined in this column, Solid Tissue Normal
(our control samples) and Primary solid Tumor
(our samples of interest). In this factor, we also want to define Solid Tissue Normal
as being our base or reference level.
group = relevel(group, ref="Solid Tissue Normal")
Next, we need to create a design matrix, which will indicate the conditions to be compared by the DE analysis. The ~
symbol represents that we are constructing a formula.
design = model.matrix(~group)
head(design)
## (Intercept) groupPrimary solid Tumor
## 1 1 1
## 2 1 0
## 3 1 1
## 4 1 1
## 5 1 1
## 6 1 1
Before performing DE analysis, we remove genes, which have low amount of counts. We transform our tcga_data
object as DGEList
, which provides functions for filtering. By default genes with counts with less than 10 reads are removed.
dge = DGEList( # creating a DGEList object
counts = assay(tcga_data),
samples = colData(tcga_data),
genes = as.data.frame(rowData(tcga_data)))
# filtering
keep = filterByExpr(dge, design) # defining which genes to keep
dge = dge[keep,, keep.lib.sizes = FALSE] # filtering the dge object
rm(keep) # use rm() to remove objects from memory if you don't need them anymore
Before we fit a model to our data, we normalize the data to minimize batch effects and technical variation with the TMM (trimmed mean of M-values) normalization method. Moreover, to apply limma on RNA-seq, we need to convert the data to have a similar variance as arrays. This is done with the VOOM method.
dge = calcNormFactors(dge, method = "TMM")
v = voom(dge, design, plot = TRUE)
Finally, using lmFit
lets fit a series of linear models, one to each of the probes. These data will then be fed to eBayes
to produce a complex object which holds a number of statistics that we can use to rank the differentially expressed genes.
fit = lmFit(v, design)
fit = eBayes(fit)
Using the function topTable
we can check the top10 genes classified as being differentially expressed. ’
topGenes = topTable(fit, coef = 1, sort.by = "p")
print(topGenes)
## source type score phase gene_id gene_type
## ENSG00000009307.16 HAVANA gene NA NA ENSG00000009307.16 protein_coding
## ENSG00000011304.22 HAVANA gene NA NA ENSG00000011304.22 protein_coding
## ENSG00000022840.16 HAVANA gene NA NA ENSG00000022840.16 protein_coding
## ENSG00000044115.21 HAVANA gene NA NA ENSG00000044115.21 protein_coding
## ENSG00000048828.17 HAVANA gene NA NA ENSG00000048828.17 protein_coding
## ENSG00000054118.15 HAVANA gene NA NA ENSG00000054118.15 protein_coding
## ENSG00000057608.17 HAVANA gene NA NA ENSG00000057608.17 protein_coding
## ENSG00000067560.13 HAVANA gene NA NA ENSG00000067560.13 protein_coding
## ENSG00000068697.7 HAVANA gene NA NA ENSG00000068697.7 protein_coding
## ENSG00000070831.17 HAVANA gene NA NA ENSG00000070831.17 protein_coding
## gene_name level hgnc_id havana_gene logFC
## ENSG00000009307.16 CSDE1 1 HGNC:29905 OTTHUMG00000012060.6 8.411134
## ENSG00000011304.22 PTBP1 2 HGNC:9583 OTTHUMG00000181789.13 7.251258
## ENSG00000022840.16 RNF10 1 HGNC:10055 OTTHUMG00000168999.17 6.823990
## ENSG00000044115.21 CTNNA1 1 HGNC:2509 OTTHUMG00000163502.5 7.418446
## ENSG00000048828.17 FAM120A 2 HGNC:13247 OTTHUMG00000020252.4 7.186905
## ENSG00000054118.15 THRAP3 2 HGNC:22964 OTTHUMG00000007866.8 6.630676
## ENSG00000057608.17 GDI2 1 HGNC:4227 OTTHUMG00000017607.10 7.926169
## ENSG00000067560.13 RHOA 1 HGNC:667 OTTHUMG00000156838.8 7.932299
## ENSG00000068697.7 LAPTM4A 2 HGNC:6924 OTTHUMG00000090750.3 8.173804
## ENSG00000070831.17 CDC42 2 HGNC:1736 OTTHUMG00000002753.10 6.993893
## AveExpr t P.Value adj.P.Val B
## ENSG00000009307.16 8.203503 124.4272 0 0 756.8189
## ENSG00000011304.22 7.489420 156.5117 0 0 850.1598
## ENSG00000022840.16 6.882473 134.9557 0 0 790.0723
## ENSG00000044115.21 7.801763 120.4779 0 0 743.9535
## ENSG00000048828.17 6.997788 128.0751 0 0 768.7852
## ENSG00000054118.15 6.365243 129.7622 0 0 774.1524
## ENSG00000057608.17 7.627059 131.0249 0 0 777.8837
## ENSG00000067560.13 8.089719 158.4214 0 0 854.8733
## ENSG00000068697.7 7.866967 124.2072 0 0 756.1619
## ENSG00000070831.17 6.925503 124.8544 0 0 758.4748
topTable
returns a table with the top genes sorted by P.value
expressing if the gene is differentially expressed.
We have also prepared a function that produces PCA plots given the voom
object created by the limma_pipeline
function. You can inspect this function and try to figure out how it works.
plot_PCA = function(voomObj, condition_variable){
group = factor(voomObj$targets[, condition_variable])
pca = prcomp(t(voomObj$E))
# Take PC1 and PC2 for the plot
plot(pca$x[, 1:2],col = group, pch = 19)
# include a legend for points
legend("bottomleft", inset = .01, levels(group), pch = 19, col = 1:length(levels(group)))
return(pca)
}
By calling the function plot_PCA
, we get a plot of the first two principal components:
res_pca = plot_PCA(limma_res$voomObj, "definition")
This plot shows that the two sample groups (tumor tissue and healthy tissue) have a well-separated RNA expression profile.
With all the information already available to us created with the limma_pipeline
function, we can also, for example, create a heatmap picturing the expression of the top20 differentially expressed genes on our samples.
# first lets get the normalized expression matrix from our limma_res object
expr_mat = as.matrix(t(limma_res$voomObj$E))
# then lets get gene names that are easier to look at
gene_names = limma_res$voomObj$genes[, "gene_name"]
# and use these to rename the genes in our expression matrix
colnames(expr_mat) = gene_names
# we want to get the top20 DE genes
# topGenes is already sorted by the adjusted p-value (in ascending order)
head(limma_res$topGenes, 20)
## source type score phase gene_id gene_type
## ENSG00000104938.18 HAVANA gene NA NA ENSG00000104938.18 protein_coding
## ENSG00000165682.14 HAVANA gene NA NA ENSG00000165682.14 protein_coding
## ENSG00000263761.3 HAVANA gene NA NA ENSG00000263761.3 protein_coding
## ENSG00000163217.2 HAVANA gene NA NA ENSG00000163217.2 protein_coding
## ENSG00000136011.15 HAVANA gene NA NA ENSG00000136011.15 protein_coding
## ENSG00000164619.10 HAVANA gene NA NA ENSG00000164619.10 protein_coding
## ENSG00000145708.11 HAVANA gene NA NA ENSG00000145708.11 protein_coding
## ENSG00000160339.16 HAVANA gene NA NA ENSG00000160339.16 protein_coding
## ENSG00000019169.10 HAVANA gene NA NA ENSG00000019169.10 protein_coding
## ENSG00000251049.2 HAVANA gene NA NA ENSG00000251049.2 lncRNA
## ENSG00000184374.3 HAVANA gene NA NA ENSG00000184374.3 protein_coding
## ENSG00000142748.13 HAVANA gene NA NA ENSG00000142748.13 protein_coding
## ENSG00000145824.13 HAVANA gene NA NA ENSG00000145824.13 protein_coding
## ENSG00000160323.19 HAVANA gene NA NA ENSG00000160323.19 protein_coding
## ENSG00000164100.9 HAVANA gene NA NA ENSG00000164100.9 protein_coding
## ENSG00000114812.13 HAVANA gene NA NA ENSG00000114812.13 protein_coding
## ENSG00000164161.10 HAVANA gene NA NA ENSG00000164161.10 protein_coding
## ENSG00000181072.11 HAVANA gene NA NA ENSG00000181072.11 protein_coding
## ENSG00000160801.14 HAVANA gene NA NA ENSG00000160801.14 protein_coding
## ENSG00000183287.14 HAVANA gene NA NA ENSG00000183287.14 protein_coding
## gene_name level hgnc_id havana_gene logFC
## ENSG00000104938.18 CLEC4M 2 HGNC:13523 OTTHUMG00000182432.4 -9.210955
## ENSG00000165682.14 CLEC1B 1 HGNC:24356 OTTHUMG00000168502.1 -7.653091
## ENSG00000263761.3 GDF2 2 HGNC:4217 OTTHUMG00000188320.2 -9.231481
## ENSG00000163217.2 BMP10 2 HGNC:20869 OTTHUMG00000129573.2 -7.947046
## ENSG00000136011.15 STAB2 2 HGNC:18629 OTTHUMG00000170056.2 -6.115969
## ENSG00000164619.10 BMPER 2 HGNC:24154 OTTHUMG00000128675.24 -6.047237
## ENSG00000145708.11 CRHBP 2 HGNC:2356 OTTHUMG00000102133.3 -6.456194
## ENSG00000160339.16 FCN2 2 HGNC:3624 OTTHUMG00000020892.2 -7.503585
## ENSG00000019169.10 MARCO 2 HGNC:6895 OTTHUMG00000131400.4 -7.202734
## ENSG00000251049.2 AC107396.1 2 <NA> OTTHUMG00000162168.2 -4.862289
## ENSG00000184374.3 COLEC10 2 HGNC:2220 OTTHUMG00000164971.2 -5.948085
## ENSG00000142748.13 FCN3 2 HGNC:3625 OTTHUMG00000005722.2 -5.842676
## ENSG00000145824.13 CXCL14 2 HGNC:10640 OTTHUMG00000129139.7 -6.656538
## ENSG00000160323.19 ADAMTS13 2 HGNC:1366 OTTHUMG00000020876.4 -3.125197
## ENSG00000164100.9 NDST3 2 HGNC:7682 OTTHUMG00000132959.5 -5.203229
## ENSG00000114812.13 VIPR1 1 HGNC:12694 OTTHUMG00000131792.9 -4.643965
## ENSG00000164161.10 HHIP 2 HGNC:14866 OTTHUMG00000161428.3 -6.505694
## ENSG00000181072.11 CHRM2 2 HGNC:1951 OTTHUMG00000155658.3 -5.523648
## ENSG00000160801.14 PTH1R 2 HGNC:9608 OTTHUMG00000133515.6 -4.145285
## ENSG00000183287.14 CCBE1 2 HGNC:29426 OTTHUMG00000180087.6 -5.409088
## AveExpr t P.Value adj.P.Val B
## ENSG00000104938.18 -3.29790933 -45.76478 5.779751e-166 1.309403e-161 368.1104
## ENSG00000165682.14 -3.36629418 -38.94459 5.371549e-142 6.084622e-138 313.1894
## ENSG00000263761.3 -2.97510418 -38.51744 2.051337e-140 1.549101e-136 309.9568
## ENSG00000163217.2 -3.56628486 -37.56620 7.416853e-137 4.200720e-133 301.4771
## ENSG00000136011.15 -0.87315516 -35.51878 4.956772e-129 2.245913e-125 284.0357
## ENSG00000164619.10 -1.73613559 -32.55930 2.563632e-117 9.679848e-114 257.0830
## ENSG00000145708.11 0.50820337 -31.77787 3.806450e-114 1.231930e-110 250.0448
## ENSG00000160339.16 -0.71251869 -31.70095 7.842429e-114 2.220878e-110 249.2956
## ENSG00000019169.10 0.02107971 -30.68852 1.136517e-109 2.860867e-106 239.7753
## ENSG00000251049.2 -5.58007121 -29.79782 5.755192e-106 1.303839e-102 229.8055
## ENSG00000184374.3 0.41557682 -28.60443 6.101200e-101 1.256570e-97 219.7627
## ENSG00000142748.13 1.97355058 -28.06573 1.191952e-98 2.250306e-95 214.5240
## ENSG00000145824.13 -0.50760130 -26.97348 5.776854e-94 1.006728e-90 203.7510
## ENSG00000160323.19 2.63405620 -26.69602 9.124846e-93 1.476596e-89 201.0231
## ENSG00000164100.9 -4.20541095 -26.44827 1.079233e-91 1.630002e-88 197.8727
## ENSG00000114812.13 0.75604779 -26.20235 1.260665e-90 1.785022e-87 196.0978
## ENSG00000164161.10 -1.63231026 -25.72424 1.523077e-88 2.029724e-85 191.2821
## ENSG00000181072.11 -4.42725147 -25.40356 3.838206e-87 4.830808e-84 187.5257
## ENSG00000160801.14 1.07294633 -25.11126 7.325049e-86 8.734157e-83 185.1695
## ENSG00000183287.14 -1.45878455 -24.98767 2.553693e-85 2.892696e-82 183.8531
# therefore we can just go ahead and select the first 20 values
top_de_genes = limma_res$topGenes$gene_name[1:20]
# we'll get the sample type data so that we can show the groups in the heatmap
sample_type = factor(limma_res$voomObj$targets$sample_type)
# define the color palette for the plot
hmcol = colorRampPalette(rev(brewer.pal(9, "RdBu")))(256)
# perform complete linkage clustering
clust_func = function(x) hclust(x, method = "complete")
# use the inverse of correlation as distance.
dist_func = function(x) as.dist((1 - cor(t(x))) / 2)
# A good looking heatmap involves a lot of parameters and tinkering
gene_heatmap = heatmap.2(
t(expr_mat[, top_de_genes]),
scale = "row", # scale the values for each gene (row)
density.info = "none", # turns off density plot inside color legend
trace = "none", # turns off trace lines inside the heat map
col = hmcol, # define the color map
labCol = FALSE, # Not showing column labels
ColSideColors = as.character(as.numeric(sample_type)), # Show colors for each response class
dendrogram = "both", # Show dendrograms for both axis
hclust = clust_func, # Define hierarchical clustering method
distfun = dist_func, # Using correlation coefficient for distance function
cexRow = 1.0, # Resize row labels
keysize = 1.25, # Size of the legend
margins = c(1,6) # Define margin spaces
)
Produce a PCA plot using gender
as condition (hint: remember that we already run the pipeline for gender). How does it look like? Are the tissues well separated or not?
Can you think about a more interesting feature to group patients? Choose one and pass it to the condition_variable
argument of the limma_pipeline
function. Make sure to save the result to a variable.
Remember that you can see all available clinical features/phenotypes with the following command:
colnames(colData(tcga_data))
You can also run the plot_PCA
function with this new condition_variable
that you chose.
Extra challenge for the brave: change the limma_pipeline
function so that it returns an arbitrary number of topGenes
(defined by the user), instead of always 100.
One analysis often performed on TCGA data is survival analysis. In short, this boils down to answering the following question: how more likely is a certain group of patients to live longer than another?
The techniques we are going to see are not, however, limited to survival (to death events) but can be applied to any experiment where patients can be divided into groups and there is an event, something happening at a specific time point.
Before we start, if you don’t have all the libraries we used previously, as well as the objects limma_res
and tcga_data
already loaded, please do so:
# Load packages
library("TCGAbiolinks")
library("limma")
library("edgeR")
library("glmnet")
library("factoextra")
library("FactoMineR")
library("caret")
library("SummarizedExperiment")
library("gplots")
library("survival")
library("survminer")
library("RColorBrewer")
library("genefilter")
# NB: make sure you set the working directory of RStudio correctly
tcga_data = readRDS(file = "tcga_data.RDS")
limma_res = readRDS(file = "limma_res.RDS")
To warm up and explain the method, we will start with an easy question: does gender influence survival in liver cancer patients?
TCGA, as mentioned before, provides a lot of clinical data for each patient. We need to extract the gender variable, and a few more besides:
# extract clinical data
clinical = tcga_data@colData
dim(clinical)
## [1] 421 64
# we are only interested in the "Primary solid Tumor" cases for survival
keep_rows = clinical$definition == "Primary solid Tumor"
keep_cols = c(
"patient",
"vital_status",
"days_to_death",
"days_to_last_follow_up",
"gender",
"ajcc_pathologic_stage"
)
# subsetting the clinical data with just the rows and cols we want to keep
clin_df = clinical[keep_rows, keep_cols]
Now we have a new dataframe, clin_df
, containing only the information that is relevant to survival analysis. In addition to gender
, we have added vital_status
(whether patient is alive or dead), ajcc_pathologic_stage
(from stage 1 to 4) and two important variables: days_to_death
, that is the number of days passed from the initial diagnosis to the patient’s death (clearly, this is only relevant for dead patients), and days_to_last_follow_up
that is the number of days passed from the initial diagnosis to the last visit.
Before we can proceed, we need to change part of this information in a way that is acceptable to the methods from the survival
package we are using:
# create a new boolean variable that has TRUE for dead patients
# and FALSE for live patients
clin_df$deceased = clin_df$vital_status == "Dead"
# create an "overall survival" variable that is equal to days_to_death
# for dead patients, and to days_to_last_follow_up for patients who
# are still alive
clin_df$overall_survival = ifelse(
clin_df$deceased, # logical vector
clin_df$days_to_death, # if vector position is true, have this value
clin_df$days_to_last_follow_up # if vector position is false, have this value
)
# show first 10 samples
head(clin_df, 10)
## DataFrame with 10 rows and 8 columns
## patient vital_status days_to_death
## <character> <character> <integer>
## TCGA-FV-A3I0-01A-11R-A22L-07 TCGA-FV-A3I0 Alive NA
## TCGA-DD-A3A6-01A-11R-A22L-07 TCGA-DD-A3A6 Dead 3258
## TCGA-BD-A3ER-01A-11R-A213-07 TCGA-BD-A3ER Alive NA
## TCGA-CC-5261-01A-01R-A131-07 TCGA-CC-5261 Dead 97
## TCGA-DD-AAVZ-01A-11R-A41C-07 TCGA-DD-AAVZ Alive NA
## TCGA-DD-AADN-01A-11R-A41C-07 TCGA-DD-AADN Alive NA
## TCGA-DD-A1EB-01A-11R-A131-07 TCGA-DD-A1EB Alive NA
## TCGA-LG-A9QD-01A-11R-A38B-07 TCGA-LG-A9QD Alive NA
## TCGA-G3-A25T-01A-11R-A16W-07 TCGA-G3-A25T Alive NA
## TCGA-XR-A8TE-01A-11R-A36F-07 TCGA-XR-A8TE Alive NA
## days_to_last_follow_up gender
## <integer> <character>
## TCGA-FV-A3I0-01A-11R-A22L-07 848 female
## TCGA-DD-A3A6-01A-11R-A22L-07 NA female
## TCGA-BD-A3ER-01A-11R-A213-07 1115 male
## TCGA-CC-5261-01A-01R-A131-07 12 male
## TCGA-DD-AAVZ-01A-11R-A41C-07 1900 male
## TCGA-DD-AADN-01A-11R-A41C-07 898 male
## TCGA-DD-A1EB-01A-11R-A131-07 2017 female
## TCGA-LG-A9QD-01A-11R-A38B-07 366 male
## TCGA-G3-A25T-01A-11R-A16W-07 1553 female
## TCGA-XR-A8TE-01A-11R-A36F-07 925 male
## ajcc_pathologic_stage deceased overall_survival
## <character> <logical> <integer>
## TCGA-FV-A3I0-01A-11R-A22L-07 Stage II FALSE 848
## TCGA-DD-A3A6-01A-11R-A22L-07 Stage II TRUE 3258
## TCGA-BD-A3ER-01A-11R-A213-07 Stage II FALSE 1115
## TCGA-CC-5261-01A-01R-A131-07 Stage II TRUE 97
## TCGA-DD-AAVZ-01A-11R-A41C-07 Stage I FALSE 1900
## TCGA-DD-AADN-01A-11R-A41C-07 Stage I FALSE 898
## TCGA-DD-A1EB-01A-11R-A131-07 Stage I FALSE 2017
## TCGA-LG-A9QD-01A-11R-A38B-07 Stage IIIA FALSE 366
## TCGA-G3-A25T-01A-11R-A16W-07 Stage IIIA FALSE 1553
## TCGA-XR-A8TE-01A-11R-A36F-07 Stage IIIA FALSE 925
Let’s now see if male and female patients have had different prognosis (in this dataset).
As a first step, we need to define a survival formula with the help of the Surv
object.
In R, formulas are special constructs of the form y ~ x
, and in the context of linear models you can see x
as the independent variable and y
as the dependent variable.
This works also for multivariate models: age ~ gender + height
is a formula that can be used to predict age from gender and height. You can refer to the documentation of formula for further examples and explanations, by typing ?formula
in a R shell.
Let’s get back to survival. We have a categorical variable, gender
, that needs to be used to separate (or, more appropriately, stratify) the available death events.
The survival
package provides us with an object, Surv
, to form a dependent variable out of the overall_survival
and deceased
information:
Surv(clin_df$overall_survival, clin_df$deceased)
## [1] 848+ 3258 1115+ 97 1900+ 898+ 2017+ 366+ 1553+ 925+ 2301+ 12+
## [13] 101 1345+ 631+ 1233+ 630+ 137+ 1302+ 2015+ 308 1295+ 848 14
## [25] 2202+ 898+ 1066+ 698+ 296 153 247 2398+ 23+ 602+ 52 1562+
## [37] 474+ 6+ 1852 942+ 1876+ 361+ 103 430+ 784+ 849+ 1098+ 27
## [49] 432 2301+ 596 1363+ 768 372+ 31 693+ 427+ 744+ 406+ 1624
## [61] 1989+ 315 706+ 632+ 91 673+ 688 848+ 829+ 415+ 519+ 36
## [73] 345+ 0+ 1694 636+ 1939+ 395+ 722+ 330+ 1229 1049+ 837 552+
## [85] 2486 2752+ 3308+ 662+ 248+ 1149 507+ 756+ 1779+ 1855+ 658+ 328+
## [97] 8+ 56 1168+ 2317+ 989+ 639 394 698+ 587+ 693 272 415
## [109] 520+ 1219+ 229+ 354+ 303+ 2116 115 1339+ 765 782+ 140 1386
## [121] 363+ 425+ 344 1560 452 359+ 564+ 195 NA+ 468+ 217 1135
## [133] 194 588+ 46 170+ 436+ 183+ 810+ 67 906+ 535 910+ 555
## [145] 555+ 1030+ 9 299 283 102 547 579+ 349 680+ 223 1067+
## [157] 538+ 6+ 6+ 2415+ 3437+ 802 928+ 1145+ 512+ 837 752 10+
## [169] 1531+ 396+ 300 214 724 558 141+ 291+ 612 2425+ 2184+ 601+
## [181] 406+ 94+ 416 180+ 660 1+ 1636+ 819+ 486+ 171 387+ 2746+
## [193] 87 554+ 594+ 409+ 9+ 3125 219+ 1450+ 314+ 365+ 562+ 1618+
## [205] 359 640+ 697+ 879+ 412+ 478+ 363+ 747+ 1531+ 655+ 366 1271
## [217] 341+ 1091+ 917+ 425 672+ 381 799+ 395+ 644+ 601 627 780+
## [229] 931 16 1351+ 574+ 638+ 361+ 0+ 322+ 615+ 711 1372 757
## [241] 2245+ 1424+ 444+ 11 20+ 951+ 1452+ 671+ 347 2513+ 453+ 2455+
## [253] 423+ 1088 1085+ 2102+ 1622 9+ 129 621+ 1791 408+ 327+ 1516+
## [265] 399+ 469 347+ 1718+ 260+ 472+ 1231+ 608+ 899 278 719+ 400+
## [277] 1008+ 0+ 854+ 15+ 729+ 1495+ 1731+ 300 520+ 649 44+ 643
## [289] 262 1685 860+ 211+ 500+ 22+ 91 827 556 585+ 21+ 30+
## [301] 3675+ 2542 566+ 3478+ 107 1490 816+ 1005 1633+ 0+ 410 1242+
## [313] 763+ 79+ 1423 65 279 303 1210 419 129 387+ 12 365
## [325] 19 250+ 2324+ 1397 476+ 34 701+ 2412+ 447+ 1085+ 1241+ 438
## [337] 233 2728+ 1567+ 2028+ 1804+ 56 570+ 1823+ 390+ 458+ 262 65
## [349] 2456 728+ 575+ 357+ 1970+ 412 0+ 373 171 608+ 449+ 2442+
## [361] 480+ 2532 1711+ 581 555+ 20+ 382+ 633 770 2131 304
This modifies our overall survival vector by adding censoring information (the +
just after the time), which requires a small digression.
This data is right censored, meaning that for some patients we only have the time of the last follow up but we don’t know if they died at a later date or not.
These patients are kept in the early stages of the analysis (eg, they are part of the survival curve) but they are dropped (or as it is said, censored) when the time of their last follow up arrives.
Now that the survival time has been tagged with the censoring, we can add the categorical independent variable gender
, and effectively create a formula
Surv(clin_df$overall_survival, clin_df$deceased) ~ clin_df$gender
We now have a survival formula that can be passed to the survfit
function to fit the survival model, and then to another function to produce the Kaplan-Meier plots. Actually, when executing the survival analysis with survfit
, we can exclude the clin_df$
if we tell the function to use clin_df
as data by using the data=
parameter.
# fit a survival model
gender_survival_fit = survfit(Surv(overall_survival, deceased) ~ gender, data = clin_df)
print(gender_survival_fit)
## Call: survfit(formula = Surv(overall_survival, deceased) ~ gender,
## data = clin_df)
##
## 1 observation deleted due to missingness
## n events median 0.95LCL 0.95UCL
## gender=female 121 51 1490 1005 2456
## gender=male 249 79 2486 1423 NA
# we produce a Kaplan Meier plot
ggsurvplot(gender_survival_fit, data = clin_df)
This Kaplan-Meier plot shows two very similar trends until almost the 2000-day mark, where females seem to have a worse survival probability. But is there a significant difference?
The difference between two such “event curves” is best tested via the logrank test, which is, fundamentally, a repeated test of independence. survminer
will add the p-value of such test if we tell it to do so:
ggsurvplot(gender_survival_fit, data = clin_df, pval = TRUE)
The p-value is non-significant, so gender alone does not significantly sway prognosis in this dataset.
If you find this strange because the curves deviate at the 2000-day mark, you have to remember that the amount of patients involved matters. At that point, only a few patients remain, and any difference is likely to not be significant.
Can we see the number of patients dying (or being “censored”) as Time increases? Indeed we can, with what is called the “at risk table”.
ggsurvplot(gender_survival_fit, data = clin_df, pval = TRUE, risk.table = TRUE, risk.table.col = "strata")
With the risk.table=TRUE
argument, we get the number of patients “at risk”, that is neither dead nor censored at a certain time point.
The argument risk.table.col="strata"
tells survminer
to colour the table in the same way as the strata, or groups, are coloured.
You can see that most of the patients die or are censored before the 2000-day mark, and therefore it makes sense that the p-value would not be significant.
Another question could be: how does tumor stage affect survival?
The ajcc_pathologic_stage
variable that TCGA provides for this tumor contains both stages and sub-stages, eg stage iiia or stage ivb. We want to join together the sub-stages, to increase the group size and reduce complexity (and thus increase the power of the logrank statistics).
# remove any of the letters "A", "B" or "C", but only if they are at the end
# of the name, eg "stage iiia" would become simply "stage iii"
# THIS IS HARD, do ask questions :)
clin_df$ajcc_pathologic_stage = gsub("[ABC]$", "", clin_df$ajcc_pathologic_stage)
# let's see how many patients we have for each stage
print(table(clin_df$ajcc_pathologic_stage))
##
## Stage I Stage II Stage III Stage IV
## 171 86 85 5
# since we have too few Stage 4 patients, we put them together with Stage IIIs
clin_df[which(clin_df$ajcc_pathologic_stage == "Stage III"), "ajcc_pathologic_stage"] = "Stage III+"
clin_df[which(clin_df$ajcc_pathologic_stage == "Stage IV"), "ajcc_pathologic_stage"] = "Stage III+"
print(table(clin_df$ajcc_pathologic_stage))
##
## Stage I Stage II Stage III+
## 171 86 90
We can now fit a new survival model with the tumor stage groups (one to four, plus the “not reported”):
tumor_survival_fit = survfit(Surv(overall_survival, deceased) ~ ajcc_pathologic_stage, data = clin_df)
# we can extract the survival p-value and print it
tumor_surv_pval = surv_pvalue(tumor_survival_fit, data = clin_df)$pval
print(tumor_surv_pval)
## [1] 3.081341e-06
# we produce a Kaplan-Meier plot from the fitted model
ggsurvplot(tumor_survival_fit, data = clin_df, pval = TRUE, risk.table = TRUE)
We get an overall p-value testing the null hypothesis that all the curves are similar at every time point. In this case, the p-value is small enough that we can reject the null hypothesis.
What we saw here is an easy way of producing Kaplan-Meier plots to investigate survival, as well as evaluating whether the survival curves are significantly different or not. A more interesting application to this is using, for example, gene expression to divide the patients into groups, to see whether up or down regulation of genes affects survival. We will see this in the next section.
Earlier, we looked at the RNASeq data for this tumor. We found some genes that are differentially expressed between the healthy and disease samples, and we also trained an Elastic Net model and investigated those predictors that are important in discriminating healthy and disease tissue.
So, taken one of the selected genes, we know that they are either up-regulated in the tumor tissue tissue and not in the normal tissue, or viceversa. But do these genes also provide an advantage, or disadvantage, regarding prognosis?
We already have the top differentially expressed genes, ordered by significance, in the limma_res$topGenes
data.frame, so we just have to take the first one.
# let's extract the table of differential expression we got earlier
genes_df = limma_res$topGenes
# print the first row, to see the gene name, the logFC value and the p-value
genes_df[1, ]
## source type score phase gene_id gene_type
## ENSG00000104938.18 HAVANA gene NA NA ENSG00000104938.18 protein_coding
## gene_name level hgnc_id havana_gene logFC
## ENSG00000104938.18 CLEC4M 2 HGNC:13523 OTTHUMG00000182432.4 -9.210955
## AveExpr t P.Value adj.P.Val B
## ENSG00000104938.18 -3.297909 -45.76478 5.779751e-166 1.309403e-161 368.1104
# get the ensembl gene id of the first row
gene_id = genes_df[1, "gene_id"]
# also get the common gene name of the first row
gene_name = genes_df[1, "gene_name"]
We now have selected a gene. Let’s visualize how much differentially expressed it is:
# get the actual expression matrix from the limma result object.
# we transpose it because we want genes in the columns and patients in the rows
expr_df = t(limma_res$voomObj$E)
# let's show the first five genes for the first five patients
expr_df[1:5, 1:5]
## ENSG00000000003.15 ENSG00000000419.13
## TCGA-FV-A3I0-01A-11R-A22L-07 8.053085 4.497253
## TCGA-DD-A3A6-11A-11R-A22L-07 7.248196 4.370416
## TCGA-DD-A3A6-01A-11R-A22L-07 4.252935 2.765850
## TCGA-BD-A3ER-01A-11R-A213-07 6.193146 3.922682
## TCGA-CC-5261-01A-01R-A131-07 6.334523 5.008292
## ENSG00000000457.14 ENSG00000000460.17
## TCGA-FV-A3I0-01A-11R-A22L-07 3.112223 1.0759349
## TCGA-DD-A3A6-11A-11R-A22L-07 2.734764 0.4347782
## TCGA-DD-A3A6-01A-11R-A22L-07 2.300924 -0.6329336
## TCGA-BD-A3ER-01A-11R-A213-07 3.250292 1.2375328
## TCGA-CC-5261-01A-01R-A131-07 4.040067 2.9286510
## ENSG00000000938.13
## TCGA-FV-A3I0-01A-11R-A22L-07 1.5845071
## TCGA-DD-A3A6-11A-11R-A22L-07 0.3215676
## TCGA-DD-A3A6-01A-11R-A22L-07 3.3273963
## TCGA-BD-A3ER-01A-11R-A213-07 2.5072647
## TCGA-CC-5261-01A-01R-A131-07 2.4610080
# visualize the gene expression distribution on the diseased samples (in black)
# versus the healthy samples (in red)
expr_diseased = expr_df[rownames(clin_df), gene_id]
expr_healthy = expr_df[setdiff(rownames(expr_df), rownames(clin_df)), gene_id]
boxplot(
expr_diseased,
expr_healthy,
names = c("Diseased", "Healthy"),
main = "Distribution of gene expression"
)
Quite so! To see if its expression also influences prognosis, we take all the expression values in the diseased samples, then take the median of them.
Patients with expression greater than the median we put in the up-regulated groups, and the others in the down-regulated group.
# get the expression values for the selected gene
clin_df$gene_value = expr_df[rownames(clin_df), gene_id]
# find the median value of the gene and print it
median_value = median(clin_df$gene_value)
median_value
## [1] -5.047521
# divide patients in two groups, up and down regulated.
# if the patient expression is greater or equal to them median we put it
# among the "up-regulated", otherwise among the "down-regulated"
clin_df$gene = ifelse(clin_df$gene_value >= median_value, "UP", "DOWN")
# we can fit a survival model, like we did in the previous section
fit = survfit(Surv(overall_survival, deceased) ~ gene, data=clin_df)
# we can extract the survival p-value and print it
pval = surv_pvalue(fit, data=clin_df)$pval
pval
## [1] 0.9492059
# and finally, we produce a Kaplan-Meier plot
ggsurvplot(fit, data=clin_df, pval=T, risk.table=T, title=paste(gene_name))
You can also save the plot to file instead of simply visualizing it:
This gene does not appear to make a difference for prognosis. But what about the other differentially expressed genes?
We are not limited to the top gene, though. We could, for example, look at the ten most differentially expressed genes, one by one, and save the survival plot to see if some of them provide a significant effect on survival.
To achieve this, we can place the previous code in a for loop, and save each result to a different file. Try it.
for (i in 1:10) {
# get the ensembl gene id of the i-th row
gene_id = genes_df[i, "gene_id"]
# also get the common gene name of the i-th row
gene_name = genes_df[i, "gene_name"]
# get the expression values for the selected gene
clin_df$gene_value = expr_df[rownames(clin_df), gene_id]
# find the median value of the gene
median_value = median(clin_df$gene_value)
# divide patients in two groups, up and down regulated.
# if the patient expression is greater or equal to them median we put it
# among the "up-regulated", otherwise among the "down-regulated"
clin_df$gene = ifelse(clin_df$gene_value >= median_value, "UP", "DOWN")
# we can now run survival like we did in the previous section
fit = survfit(Surv(overall_survival, deceased) ~ gene, data=clin_df)
survp = ggsurvplot(fit, data=clin_df, pval=T, risk.table=T, title=paste(gene_name))
# we can save the survival plot to file, try it by uncommenting it
# ggsave(file=paste0(gene_name, ".pdf"), print(survp))
# let's also save the p-value for later.. you'll see why :)
genes_df[i, "surv_pv"] = surv_pvalue(fit, data=clin_df)$pval
}
Now we have generated ten plots, and likely found some interesting candidates with significant p-value. Since we performed a statistical test multiple times (a task called multiple testing), we need to correct all the p-values.
The function p.adjust
helps us do this. Read how to use it with ?p.adjust
, and make sure to select the Benjamini-Hochberg method (also called fdr
).
# take the 10 pvalues you produced earlier, and put them in a vector called vec_pvalues.
vec_pvalues = genes_df[1:10, "surv_pv"]
# Then apply the Benjamini-Hochberg procedure, also called the FDR procedure
p.adjust(vec_pvalues, method = "fdr")
## [1] 0.949205853 0.007030578 0.527638992 0.860309183 0.422876624 0.298142692
## [7] 0.030626886 0.212032705 0.860309183 0.012962495
After you do this, you will notice that some of the p-values that were significant are now insignificant.
This is important to remember when applying statistical procedures multiple times: if you keep trying, there’s always a chance of getting a significant p-value when the null hypothesis is actually true.
You must, therefore, control for this chance via a multiple test correction procedure.
# take the 10 pvalues we accumulated earlier and apply the Benjamini-Hochberg procedure,
# also called the FDR procedure
adjusted_p_values = p.adjust(genes_df[1:10, "surv_pv"], method="fdr")
# add these values as a new column in the genes_df dataframe
genes_df[1:10, "surv_pv_corr"] = adjusted_p_values
# let's show them in a nice tabular way
genes_df[1:10, c("gene_name", "surv_pv", "surv_pv_corr")]
## gene_name surv_pv surv_pv_corr
## ENSG00000104938.18 CLEC4M 0.9492058525 0.949205853
## ENSG00000165682.14 CLEC1B 0.0007030578 0.007030578
## ENSG00000263761.3 GDF2 0.3693472946 0.527638992
## ENSG00000163217.2 BMP10 0.7742782646 0.860309183
## ENSG00000136011.15 STAB2 0.2537259747 0.422876624
## ENSG00000164619.10 BMPER 0.1490713459 0.298142692
## ENSG00000145708.11 CRHBP 0.0091880658 0.030626886
## ENSG00000160339.16 FCN2 0.0848130819 0.212032705
## ENSG00000019169.10 MARCO 0.7098763602 0.860309183
## ENSG00000251049.2 AC107396.1 0.0025924990 0.012962495
Whenever we perform a statistical test, there is a chance to produce a “discovery”, or significant result, that does not in fact correspond to a ground truth (that is: despite a significant p-value, the null hypothesis is true).
That is because “significance” is an arbitrary probabilistic cutoff. In many fields, a 5% chance of rejecting the null hypothesis when, in fact, it is true is widely accepted. Other fields or applications require much stricter cutoffs.
Can you guess what would happen if you performed a multitude of such tests, each at a significance level of 5%? In the worst case (that is: all null hypotheses are true), you might get an incorrectly-significant test every 20 or so.
Those wrongly-rejected null hypotheses are called false positives, and if you don’t control for it they will impede your future research efforts. This is very relevant in genomics: when we check the expression of tens of thousands of genes for an effect on survival, for example, we don’t want to end up with a bunch of candidates that won’t hold up in replication experiments.
Correction methods like the Benjamini-Hochberg (also called the “False Discovery Rate” method) help us control the amount of false positives that we are willing to accept, by further rejecting the weakest “discoveries” we’ve made in a multiple-testing setup - like today’s Exercise.
Perform the following tasks.
Can you see nice clusters in the dendrogram?
What about genes associated to each group? Are they associated to some particular biological function? Use differential expression analysis and GO enrichment analysis to solve this task.
Check if groups of patients are associated to survival, tumour grade or any other clinical variable. You can use the table function for some of these analysis.
Retrieve the following numbers from the data: how many patients are dead or alive, how many patients were in which tumor stage and how many patients had a prior malignancy. You can do this using the table function.
Good luck!
Now, we will explore the use of a machine learning method to classify an unseen sample as being a tumor or not. To achieve this goal we are going to build first a simple linear model (with feature selection), and then an Elastic Net model. For this, we need to split the data into two sets: a training set, which we will use to train our model, and a testing set. The test data serves as an independent dataset to validate our results. It is important that you do not use test data to optimize your results or this will include bias in the classifier.
First let’s start by extracting the data that we are going to use to build our model. We want the expression data that has already been normalized and a clinical feature which divides our data into different groups, such as tumor vs. non-tumor or tumor stage. We can get the normalized expression values from limma_res$voomObj$E
and the type of sample is determined by the definition
column.
limma_res = readRDS(file = "limma_res.RDS")
# Transpose and make it into a matrix object
d_mat = as.matrix(t(limma_res$voomObj$E))
# As before, we want this to be a factor
d_resp = as.factor(limma_res$voomObj$targets$definition)
With the data in the correct format we can now divide it into a train set and a test set. We will use the function createDataPartition
which creates a vector of booleans (TRUE
or FALSE
) that we can then use to subset the matrix in this case leaving 75% of samples for training and 25% for testing.
# Divide data into training and testing set
# Set (random-number-generator) seed so that results are consistent between runs
set.seed(42)
train_ids = createDataPartition(d_resp, p = 0.75, list = FALSE)
x_train = d_mat[train_ids, ]
x_test = d_mat[-train_ids, ]
y_train = d_resp[train_ids]
y_test = d_resp[-train_ids]
x_train
and y_train
are the data we will use to train our model, where x
is the matrix with the normalized expression values and y
is the vector with the response variable, Primary solid Tumor
and Solid Tissue Normal
.
Following the same logic, x_test
and y_test
are the matrix with normalized expression values and the response variable respectively. Again, we will only use these (*_test
) to perform a prediction and evaluate how good this prediction was after the training process has finished.
We will train an Elastic Net model, which is a generalized linear model that combines the best of two other models: LASSO and Ridge Regression. Ridge Regression is often good at doing predictions but its results are not very interpretable. LASSO is good at picking up small signals from lots of noise but it tends to minimize redundancy so if there are two genes that are equally good predictors (features with high correlation) it will tend to select one. Elastic Net is a balance between both methods, it selects the genes or groups of genes (if they are correlated) that best predict each of the conditions and use these to build a model that will then be used for classification.
We can then look at these genes individually to see if some interesting gene of biological relevance for the classification problem is selected. When using Elastic Net there are other parameters than we have to set, specifically alpha
. This parameter will define if the Elastic Net will behave more like LASSO (alpha = 1
) or like Ridge Regression (alpha = 0
). For simplicity we will set it to 0.5
however in a real setting we would probably vary this value in order to find the best model (minimizing the error).
# Train model on training dataset using cross-validation
res = cv.glmnet(
x = x_train,
y = y_train,
alpha = 0.5,
family = "binomial"
)
After training the model, we can now evaluate it against our test-dataset. The result from cv.glmnet
is a complex object that, between other data, holds the coefficients for our model and the mean error found during training.
# Test/Make prediction on test dataset
y_pred = predict(res, newx = x_test, type = "class", s = "lambda.min")
A confusion matrix is a simple table that compares the predictions from our model against their real values. Therefore, it shows us the true positives, true negatives, false positives and false negatives. We can use it to compute a number of accuracy metrics that we can then use to understand how good our model actually is.
confusion_matrix = table(y_pred, y_test)
# Evaluation statistics
print(confusion_matrix)
## y_test
## y_pred Primary solid Tumor Solid Tissue Normal
## Primary solid Tumor 91 0
## Solid Tissue Normal 1 12
print(paste0("Sensitivity: ", sensitivity(confusion_matrix)))
## [1] "Sensitivity: 0.989130434782609"
print(paste0("Specificity: ", specificity(confusion_matrix)))
## [1] "Specificity: 1"
print(paste0("Precision: ", precision(confusion_matrix)))
## [1] "Precision: 1"
As you see, for this data and under the current parameters, Elastic Net has great accuracy.
We can now take a look at the genes (coefficients), that Elastic Net selected to build its model.
# Getting genes that contribute for the prediction
res_coef = coef(res, s = "lambda.min") # the "coef" function returns a sparse matrix
dim(res_coef)
## [1] 22656 1
head(res_coef) # in a sparse matrix the "." represents the value of zero
## 6 x 1 sparse Matrix of class "dgCMatrix"
## s1
## (Intercept) -3.082697
## ENSG00000000003.15 .
## ENSG00000000419.13 .
## ENSG00000000457.14 .
## ENSG00000000460.17 .
## ENSG00000000938.13 .
Of course, the number of coefficients is large (there are many genes!). We only want to consider coefficients with non-zero values, as these represent variables (genes) selected by the Elastic Net.
# get coefficients with non-zero values
res_coef = res_coef[res_coef[,1] != 0,]
# note how performing this operation changed the type of the variable
head(res_coef)
## (Intercept) ENSG00000024526.17 ENSG00000043355.12 ENSG00000066279.18
## -3.082696660 -0.035474576 -0.000455808 -0.024301070
## ENSG00000086991.13 ENSG00000087237.12
## -0.047704545 0.040470299
# remove first coefficient as this is the intercept, a variable of the model itself
res_coef = res_coef[-1]
relevant_genes = names(res_coef) # get names of the (non-zero) variables.
length(relevant_genes) # number of selected genes
## [1] 100
head(relevant_genes) # few select genes
## [1] "ENSG00000024526.17" "ENSG00000043355.12" "ENSG00000066279.18"
## [4] "ENSG00000086991.13" "ENSG00000087237.12" "ENSG00000093009.11"
You might not know your Ensembl gene annotation by heart, so we can get the common gene name from limma_res$voomObj$genes
as in this table we can find the ensembl to gene name correspondence.
head(limma_res$voomObj$genes)
## source type score phase gene_id gene_type
## ENSG00000000003.15 HAVANA gene NA NA ENSG00000000003.15 protein_coding
## ENSG00000000419.13 HAVANA gene NA NA ENSG00000000419.13 protein_coding
## ENSG00000000457.14 HAVANA gene NA NA ENSG00000000457.14 protein_coding
## ENSG00000000460.17 HAVANA gene NA NA ENSG00000000460.17 protein_coding
## ENSG00000000938.13 HAVANA gene NA NA ENSG00000000938.13 protein_coding
## ENSG00000000971.16 HAVANA gene NA NA ENSG00000000971.16 protein_coding
## gene_name level hgnc_id havana_gene
## ENSG00000000003.15 TSPAN6 2 HGNC:11858 OTTHUMG00000022002.2
## ENSG00000000419.13 DPM1 2 HGNC:3005 OTTHUMG00000032742.2
## ENSG00000000457.14 SCYL3 2 HGNC:19285 OTTHUMG00000035941.6
## ENSG00000000460.17 C1orf112 2 HGNC:25565 OTTHUMG00000035821.9
## ENSG00000000938.13 FGR 2 HGNC:3697 OTTHUMG00000003516.3
## ENSG00000000971.16 CFH 1 HGNC:4883 OTTHUMG00000035607.6
relevant_gene_names = limma_res$voomObj$genes[relevant_genes, "gene_name"]
head(relevant_gene_names) # few select genes (with readable names now)
## [1] "DEPDC1" "ZIC2" "ASPM" "NOX4" "CETP" "CDC45"
Are there any genes of particular relevance?
Did limma and Elastic Net select some of the same genes? We can check the common genes between the two results by using the intersect
function.
print(intersect(limma_res$topGenes$gene_id, relevant_genes))
## [1] "ENSG00000104938.18" "ENSG00000136011.15" "ENSG00000251049.2"
## [4] "ENSG00000160323.19" "ENSG00000100362.13" "ENSG00000223922.1"
## [7] "ENSG00000126838.10" "ENSG00000183166.11" "ENSG00000087237.12"
## [10] "ENSG00000123454.12" "ENSG00000228842.3" "ENSG00000250266.2"
## [13] "ENSG00000260015.1" "ENSG00000184809.13"
Of note, we do not expect a high overlap between genes selected by limma and Elastic net. The reason for this is the fact Elastic Net criteria bias the selection of genes, which are not highly correlated against each other, while not such bias is present in limma.
Finally we can take a look at how our samples cluster together by running an hierarchical clustering algorithm. We will only be looking at the genes Elastic Net found and use these to cluster the samples. The genes highlighted in green are the ones that limma had also selected as we’ve seen before. The samples highlighted in red are Solid Tissue Normal
, the samples highlighted in black are Primary solid Tumor
.
# define the color palette for the plot
hmcol = colorRampPalette(rev(brewer.pal(9, "RdBu")))(256)
# perform complete linkage clustering
clust = function(x) hclust(x, method = "complete")
# use the inverse of correlation as distance.
dist = function(x) as.dist((1 - cor(t(x)))/2)
# Show green color for genes that also show up in DE analysis
colorLimmaGenes = ifelse(
# Given a vector of boolean values
(relevant_genes %in% limma_res$topGenes$gene_id),
"green", # if true, return green for that value
"white" # if false, return white for that value
)
# As you've seen a good looking heatmap involves a lot of parameters
d_mat_use = t(d_mat[,relevant_genes])
rownames(d_mat_use) = relevant_gene_names
gene_heatmap = heatmap.2(
#t(d_mat[,relevant_genes]),
d_mat_use,
scale = "row", # scale the values for each gene (row)
density.info = "none", # turns off density plot inside color legend
trace = "none", # turns off trace lines inside the heat map
col = hmcol, # define the color map
labRow = relevant_gene_names, # use gene names instead of ensembl annotation
RowSideColors = colorLimmaGenes,
labCol = FALSE, # Not showing column labels
ColSideColors = as.character(as.numeric(d_resp)), # Show colors for each response class
dendrogram = "both", # Show dendrograms for both axis
hclust = clust, # Define hierarchical clustering method
distfun = dist, # Using correlation coefficient for distance function
cexRow = .6, # Resize row labels
margins = c(1,5) # Define margin spaces
)
As you’ve seen, selected genes group into two classes: genes highly expressed in tumors vs. genes in control. Interestingly, genes also detected by DE analysis are only associated to high expression in the control group. One interesting question is, are selected genes (up in control or up in tumor) associated to any type of common biological problem? Try to do a GO analysis on them.
# Using the same method as in Day-2, get the dendrogram from the heatmap
# and cut it to get the 2 classes of genes
# Extract the hierarchical cluster from heatmap to class "hclust"
hc = as.hclust(gene_heatmap$rowDendrogram)
# Cut the tree into 2 groups, up-regulated in tumor and up-regulated in control
clusters = cutree(hc, k = 2)
table(clusters)
## clusters
## 1 2
## 59 41
# selecting just a few columns so that its easier to visualize the table
gprofiler2_cols = c("significant", "p_value", "intersection_size", "term_id", "term_name")
# Group 1, up in tumor
gprof_tumor_result = gost(names(clusters[clusters %in% 1]))
gprof_tumor_result[["result"]][, gprofiler2_cols]
## significant p_value intersection_size term_id
## 1 TRUE 0.049931693 1 CORUM:7462
## 2 TRUE 0.008956892 10 GO:0098590
## 3 TRUE 0.018041895 2 GO:0098651
## 4 TRUE 0.003683145 6 HP:0001274
## 5 TRUE 0.033448177 3 REAC:R-HSA-2022090
## term_name
## 1 GABA-A receptor (GABRA1, GABRB2, GABRD)
## 2 plasma membrane region
## 3 basement membrane collagen trimer
## 4 Agenesis of corpus callosum
## 5 Assembly of collagen fibrils and other multimeric structures
# Group 2, up in control
gprof_control_result = gost(names(clusters[clusters %in% 2]))
gprof_control_result[["result"]][, gprofiler2_cols]
## significant p_value intersection_size term_id term_name
## 1 TRUE 0.0306667 18 GO:0071944 cell periphery
We can also quickly visualize the results for tumor:
gostplot(gprof_tumor_result, interactive = FALSE)
And for control:
gostplot(gprof_control_result, interactive = FALSE)
Another way to reduce dimensionality is through the use of variance filtering. We can use the varFilter
function to do this.
# retain only a small subset of the genes (see documentation for ?varFilter)
d_mat = varFilter(limma_res$voomObj$E, var.func = IQR, var.cutoff = 0.95)
# transpose the matrix, so that it has the same shape as the d_mat we used at the beginning
d_mat = t(d_mat)
# show the dimensions of the matrix
print(dim(d_mat))
## [1] 421 1133
This function takes the normalized RNASeq data stored in the limma_res
object, and returns a matrix of the same form. What varFilter
does is calculate the interquartile range (IQR
) for all genes. It then removes 95% of the genes, starting with those with lower IQR. Therefore, only 5% of the genes will be retained - those with the highest dispersion, and therefore possibly the most useful information. This can easily be understood that remembering that a gene that has the exact same expression across all samples, has a variance (and IQR) of zero. We definitely want to remove those.
Run now again the commands to train the elastic net model, and to evaluate it. Has the performance increased or decreased? Are there more or less variables selected?
Remember to also re-generate your x_*
training and test data (it is not needed for the response, because that hasn’t changed) with the new d_mat
:
# size before
print(dim(x_train))
## [1] 317 22655
print(dim(x_test))
## [1] 104 22655
x_train = d_mat[train_ids, ]
x_test = d_mat[-train_ids, ]
# size after
print(dim(x_train))
## [1] 317 1133
print(dim(x_test))
## [1] 104 1133
If you don’t do this, x_train
and x_test
will still contain all 22655 genes, instead of only the 1133 we have selected.