1 Intro

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:

  1. Download the data (clinical and expression) from TGCA
  2. Processing of the data (normalization) and saving it locally using simple table formats.
  3. Unsupervised analysis includes differential expression, PCA and clustering.
  4. Build a machine learning model (classifier) to predict cancer.
  5. Perform survival analysis of molecular markers detected in previous analysis.

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")
library("limma")
library("edgeR")
library("glmnet")
library("factoextra")
library("FactoMineR")
library("caret")
library("SummarizedExperiment")
library("gplots")
library("survival")
library("survminer")
library("RColorBrewer")
library("gProfileR")
library("genefilter")

2 TCGA data

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
## 1  TCGA-BRCA
## 2  GENIE-MSK
## 3 GENIE-VICC
## 4  GENIE-UHN
## 5    CPTAC-2
## 6    CMI-ASC
##                                                                         name
## 1                                                  Breast Invasive Carcinoma
## 2 AACR Project GENIE - Contributed by Memorial Sloan Kettering Cancer Center
## 3        AACR Project GENIE - Contributed by Vanderbilt-Ingram Cancer Center
## 4        AACR Project GENIE - Contributed by Princess Margaret Cancer Centre
## 5                                                 CPTAC-Breast, Colon, Ovary
## 6                          Count Me In (CMI): The Angiosarcoma (ASC) Project

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] 11762
## 
## $data_categories
##   file_count case_count               data_category
## 1        423        377                    Clinical
## 2       2122        376     Transcriptome Profiling
## 3       1654        377            Sequencing Reads
## 4       1634        377                 Biospecimen
## 5       2283        376       Copy Number Variation
## 6        430        377             DNA Methylation
## 7       3032        375 Simple Nucleotide Variation
## 8        184        184          Proteome Profiling
## 
## $case_count
## [1] 377
## 
## $file_size
## [1] 1.780846e+13

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 HTSeq.

Note that performing this query will take a few of minutes

query_TCGA = GDCquery(
  project = "TCGA-LIHC",
  data.category = "Transcriptome Profiling", # parameter enforced by GDCquery
  experimental.strategy = "RNA-Seq",
  workflow.type = "HTSeq - 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] "access"                    "cases"                    
##  [5] "file_name"                 "submitter_id"             
##  [7] "data_category"             "type"                     
##  [9] "file_size"                 "created_datetime"         
## [11] "md5sum"                    "updated_datetime"         
## [13] "file_id"                   "data_type"                
## [15] "state"                     "experimental_strategy"    
## [17] "version"                   "data_release"             
## [19] "project"                   "analysis_id"              
## [21] "analysis_state"            "analysis_submitter_id"    
## [23] "analysis_workflow_link"    "analysis_workflow_type"   
## [25] "analysis_workflow_version" "sample_type"              
## [27] "is_ffpe"                   "cases.submitter_id"       
## [29] "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"       "Primary Tumor"       "Primary Tumor"      
## [4] "Primary Tumor"       "Solid Tissue Normal" "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 Solid Tumors). For simplicity, we will ignore the small class of recurrent solid tumors. Therefore, we will redo the query as

query_TCGA = GDCquery(
  project = "TCGA-LIHC",
  data.category = "Transcriptome Profiling", # parameter enforced by GDCquery
  experimental.strategy = "RNA-Seq",
  workflow.type = "HTSeq - 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 startign with a directory “GDCdata”.

Let us now download the files specified in the query.

GDCdownload(query = query_TCGA)

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 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 downloaded the data.

tcga_data = GDCprepare(query_TCGA)

We can then check the size of the object with the command.

dim(tcga_data)
## [1] 56602   421

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.

# 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"              "sample_id"                  
##  [9] "sample_type"                 "days_to_collection"         
## [11] "state"                       "initial_weight"             
## [13] "pathology_report_uuid"       "submitter_id"               
## [15] "oct_embedded"                "is_ffpe"                    
## [17] "tissue_type"                 "synchronous_malignancy"     
## [19] "ajcc_pathologic_stage"       "days_to_diagnosis"          
## [21] "treatments"                  "last_known_disease_status"  
## [23] "tissue_or_organ_of_origin"   "days_to_last_follow_up"     
## [25] "primary_diagnosis"           "age_at_diagnosis"           
## [27] "year_of_diagnosis"           "prior_malignancy"           
## [29] "prior_treatment"             "ajcc_staging_system_edition"
## [31] "ajcc_pathologic_t"           "morphology"                 
## [33] "ajcc_pathologic_n"           "ajcc_pathologic_m"          
## [35] "classification_of_tumor"     "diagnosis_id"               
## [37] "site_of_resection_or_biopsy" "icd_10_code"                
## [39] "tumor_grade"                 "progression_or_recurrence"  
## [41] "alcohol_history"             "exposure_id"                
## [43] "vital_status"                "gender"                     
## [45] "race"                        "ethnicity"                  
## [47] "age_at_index"                "days_to_birth"              
## [49] "year_of_birth"               "demographic_id"             
## [51] "days_to_death"               "year_of_death"              
## [53] "bcr_patient_barcode"         "primary_site"               
## [55] "project_id"                  "disease_type"               
## [57] "releasable"                  "name"                       
## [59] "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] 56602   421
head(assay(tcga_data)[,1:10]) # expression of first 6 genes and first 10 samples
##                 TCGA-DD-AAD8-01A-11R-A41C-07 TCGA-O8-A75V-01A-11R-A32O-07
## ENSG00000000003                         2482                         6287
## ENSG00000000005                            2                            0
## ENSG00000000419                          964                          993
## ENSG00000000457                          454                          834
## ENSG00000000460                          164                          277
## ENSG00000000938                          127                          226
##                 TCGA-CC-A9FS-01A-11R-A37K-07 TCGA-DD-AACK-01A-11R-A41C-07
## ENSG00000000003                        33015                        10855
## ENSG00000000005                           13                            0
## ENSG00000000419                         1250                         3026
## ENSG00000000457                          574                         1208
## ENSG00000000460                          146                          486
## ENSG00000000938                          136                          276
##                 TCGA-DD-A39Z-11A-21R-A213-07 TCGA-DD-A4NQ-01A-21R-A28V-07
## ENSG00000000003                         3865                         2645
## ENSG00000000005                            1                            0
## ENSG00000000419                          709                          709
## ENSG00000000457                          399                          666
## ENSG00000000460                           85                          334
## ENSG00000000938                          153                          327
##                 TCGA-DD-AADM-01A-11R-A41C-07 TCGA-G3-A7M7-01A-12R-A352-07
## ENSG00000000003                         3888                         2634
## ENSG00000000005                            2                            0
## ENSG00000000419                          905                         1224
## ENSG00000000457                          518                          258
## ENSG00000000460                          135                           42
## ENSG00000000938                           41                          121
##                 TCGA-DD-A1EC-11A-11R-A131-07 TCGA-DD-AAD5-01A-11R-A41C-07
## ENSG00000000003                         3428                         1523
## ENSG00000000005                            5                            1
## ENSG00000000419                          821                         1717
## ENSG00000000457                          502                         1092
## ENSG00000000460                          537                          265
## ENSG00000000938                          278                          169
head(rowData(tcga_data))     # ensembl id and gene id of the first 6 genes.
## DataFrame with 6 rows and 3 columns
##                 ensembl_gene_id external_gene_name original_ensembl_gene_id
##                     <character>        <character>              <character>
## ENSG00000000003 ENSG00000000003             TSPAN6       ENSG00000000003.13
## ENSG00000000005 ENSG00000000005               TNMD        ENSG00000000005.5
## ENSG00000000419 ENSG00000000419               DPM1       ENSG00000000419.11
## ENSG00000000457 ENSG00000000457              SCYL3       ENSG00000000457.12
## ENSG00000000460 ENSG00000000460           C1orf112       ENSG00000000460.15
## ENSG00000000938 ENSG00000000938                FGR       ENSG00000000938.11

Finally, we can use some core functionality of R to save the TCGA_data as a .RDS file. This is faster than repeating the previous operations and useful if you need to work in your data for several days.

# 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")

3 RNASeq Normalization

3.1 Defining a pipeline

Basics

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:

  • A complex object, resulting from running voom, this contains the TMM+voom normalized data;
  • A complex object, resulting from running eBayes, this contains the the fitted model plus a number of statistics related to each of the probes;
  • A simple table, resulting from running 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"
)

Details

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                        1
## 3           1                        1
## 4           1                        1
## 5           1                        0
## 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)
##                 ensembl_gene_id external_gene_name original_ensembl_gene_id
## ENSG00000003402 ENSG00000003402              CFLAR       ENSG00000003402.18
## ENSG00000009307 ENSG00000009307              CSDE1       ENSG00000009307.14
## ENSG00000011304 ENSG00000011304              PTBP1       ENSG00000011304.15
## ENSG00000022840 ENSG00000022840              RNF10       ENSG00000022840.14
## ENSG00000044115 ENSG00000044115             CTNNA1       ENSG00000044115.19
## ENSG00000048828 ENSG00000048828            FAM120A       ENSG00000048828.15
## ENSG00000054118 ENSG00000054118             THRAP3       ENSG00000054118.12
## ENSG00000057608 ENSG00000057608               GDI2       ENSG00000057608.15
## ENSG00000058262 ENSG00000058262            SEC61A1        ENSG00000058262.8
## ENSG00000063244 ENSG00000063244              U2AF2       ENSG00000063244.11
##                    logFC  AveExpr        t P.Value adj.P.Val        B
## ENSG00000003402 6.541412 6.228545 119.8501       0         0 741.9303
## ENSG00000009307 8.475034 8.249272 124.8492       0         0 758.1722
## ENSG00000011304 7.316926 7.536783 157.8125       0         0 853.5255
## ENSG00000022840 6.943851 6.979142 138.3770       0         0 800.2450
## ENSG00000044115 7.482810 7.848214 122.1962       0         0 749.6892
## ENSG00000048828 7.287580 7.074153 127.0113       0         0 765.3961
## ENSG00000054118 6.699846 6.416746 129.7490       0         0 774.1237
## ENSG00000057608 7.990418 7.673111 132.7447       0         0 783.1625
## ENSG00000058262 8.162078 8.464159 118.8233       0         0 738.2183
## ENSG00000063244 6.232492 6.553173 123.4525       0         0 753.9464

topTable returns a table with the top genes sorted by P.value expressing if the gene is differentially expressed.

3.2 Visualization

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[,"external_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)
##                 ensembl_gene_id external_gene_name original_ensembl_gene_id
## ENSG00000104938 ENSG00000104938             CLEC4M       ENSG00000104938.15
## ENSG00000182566 ENSG00000182566             CLEC4G       ENSG00000182566.11
## ENSG00000165682 ENSG00000165682             CLEC1B       ENSG00000165682.13
## ENSG00000263761 ENSG00000263761               GDF2        ENSG00000263761.2
## ENSG00000136011 ENSG00000136011              STAB2       ENSG00000136011.13
## ENSG00000163217 ENSG00000163217              BMP10        ENSG00000163217.1
## ENSG00000164619 ENSG00000164619              BMPER        ENSG00000164619.7
## ENSG00000145708 ENSG00000145708              CRHBP        ENSG00000145708.9
## ENSG00000160339 ENSG00000160339               FCN2       ENSG00000160339.14
## ENSG00000019169 ENSG00000019169              MARCO       ENSG00000019169.10
## ENSG00000129965 ENSG00000129965           INS-IGF2       ENSG00000129965.12
## ENSG00000251049 ENSG00000251049         AC107396.1        ENSG00000251049.2
## ENSG00000184374 ENSG00000184374            COLEC10        ENSG00000184374.2
## ENSG00000142748 ENSG00000142748               FCN3       ENSG00000142748.11
## ENSG00000160323 ENSG00000160323           ADAMTS13       ENSG00000160323.17
## ENSG00000145824 ENSG00000145824             CXCL14       ENSG00000145824.11
## ENSG00000126759 ENSG00000126759                CFP       ENSG00000126759.11
## ENSG00000164100 ENSG00000164100              NDST3        ENSG00000164100.8
## ENSG00000114812 ENSG00000114812              VIPR1       ENSG00000114812.11
## ENSG00000181072 ENSG00000181072              CHRM2       ENSG00000181072.10
##                     logFC    AveExpr         t       P.Value     adj.P.Val
## ENSG00000104938 -9.212475 -3.2311496 -45.86940 2.606088e-166 5.879855e-162
## ENSG00000182566 -8.283978 -1.1182816 -41.56486 1.742765e-151 1.966014e-147
## ENSG00000165682 -8.258422 -2.9700126 -40.79301 9.990240e-149 7.513326e-145
## ENSG00000263761 -8.916355 -3.6127812 -40.37238 3.280111e-147 1.850147e-143
## ENSG00000136011 -6.285843 -0.6197506 -36.10281 2.768592e-131 1.249299e-127
## ENSG00000163217 -6.138989 -5.1816982 -34.46353 6.600369e-125 2.481959e-121
## ENSG00000164619 -6.095424 -1.7271465 -32.52263 3.622110e-117 1.167458e-113
## ENSG00000145708 -6.470215  0.5585480 -31.97581 5.969599e-115 1.683576e-111
## ENSG00000160339 -7.525154 -0.6648890 -31.90568 1.151973e-114 2.887869e-111
## ENSG00000019169 -7.222976  0.0703698 -30.81685 3.364856e-110 7.591788e-107
## ENSG00000129965 -7.634855 -3.6880364 -30.73844 7.094370e-110 1.455120e-106
## ENSG00000251049 -5.092670 -5.4731691 -30.48412 8.013912e-109 1.506749e-105
## ENSG00000184374 -5.822163 -0.1748602 -29.04118 8.705374e-103  1.510851e-99
## ENSG00000142748 -5.860437  2.0206527 -28.23203  2.339277e-99  3.769911e-96
## ENSG00000160323 -3.143146  2.6828863 -27.12961  1.230586e-94  1.850966e-91
## ENSG00000145824 -6.661485 -0.4475882 -27.10649  1.547701e-94  2.182452e-91
## ENSG00000126759 -4.134678  1.6986979 -27.09318  1.766176e-94  2.344027e-91
## ENSG00000164100 -5.225484 -4.1590560 -26.63459  1.687796e-92  2.115558e-89
## ENSG00000114812 -4.653771  0.9878334 -26.18523  1.500524e-90  1.781833e-87
## ENSG00000181072 -5.549730 -4.3860034 -25.53111  1.065281e-87  1.201744e-84
##                        B
## ENSG00000104938 368.9519
## ENSG00000182566 335.4681
## ENSG00000165682 328.8327
## ENSG00000263761 325.2796
## ENSG00000136011 289.2487
## ENSG00000163217 273.0728
## ENSG00000164619 256.7496
## ENSG00000145708 251.8997
## ENSG00000160339 251.2168
## ENSG00000019169 240.9964
## ENSG00000129965 239.8700
## ENSG00000251049 236.3856
## ENSG00000184374 223.9812
## ENSG00000142748 216.1495
## ENSG00000160323 205.3172
## ENSG00000145824 205.0680
## ENSG00000126759 204.9521
## ENSG00000164100 199.7390
## ENSG00000114812 195.9300
## ENSG00000181072 188.8227
# therefore we can just go ahead and select the first 20 values
top_de_genes = limma_res$topGenes$external_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
)

3.3 Exercise

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.

4 Survival Analysis

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("gProfileR")
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  60
# we are only interested in the "Primary solid Tumor" cases for survival
clin_df = clinical[clinical$definition == "Primary solid Tumor",
                    c("patient",
                      "vital_status",
                      "days_to_death",
                      "days_to_last_follow_up",
                      "gender",
                      "ajcc_pathologic_stage")]

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,
                                   clin_df$days_to_death,
                                   clin_df$days_to_last_follow_up)

# show first 10 samples
head(clin_df)
## DataFrame with 6 rows and 8 columns
##                                   patient vital_status days_to_death
##                               <character>  <character>     <integer>
## TCGA-DD-AAD8-01A-11R-A41C-07 TCGA-DD-AAD8        Alive            NA
## TCGA-O8-A75V-01A-11R-A32O-07 TCGA-O8-A75V        Alive            NA
## TCGA-CC-A9FS-01A-11R-A37K-07 TCGA-CC-A9FS        Alive            NA
## TCGA-DD-AACK-01A-11R-A41C-07 TCGA-DD-AACK        Alive            NA
## TCGA-DD-A4NQ-01A-21R-A28V-07 TCGA-DD-A4NQ         Dead           373
## TCGA-DD-AADM-01A-11R-A41C-07 TCGA-DD-AADM         Dead            12
##                              days_to_last_follow_up      gender
##                                           <integer> <character>
## TCGA-DD-AAD8-01A-11R-A41C-07                   1219      female
## TCGA-O8-A75V-01A-11R-A32O-07                    538        male
## TCGA-CC-A9FS-01A-11R-A37K-07                    211        male
## TCGA-DD-AACK-01A-11R-A41C-07                      9        male
## TCGA-DD-A4NQ-01A-21R-A28V-07                     NA        male
## TCGA-DD-AADM-01A-11R-A41C-07                     NA        male
##                              ajcc_pathologic_stage  deceased overall_survival
##                                        <character> <logical>        <integer>
## TCGA-DD-AAD8-01A-11R-A41C-07               Stage I     FALSE             1219
## TCGA-O8-A75V-01A-11R-A32O-07               Stage I     FALSE              538
## TCGA-CC-A9FS-01A-11R-A37K-07              Stage II     FALSE              211
## TCGA-DD-AACK-01A-11R-A41C-07               Stage I     FALSE                9
## TCGA-DD-A4NQ-01A-21R-A28V-07              Stage II      TRUE              373
## TCGA-DD-AADM-01A-11R-A41C-07              Stage II      TRUE               12

Let’s now see if male and female patients have had different prognosis (in this dataset).

4.1 Kaplan-Meier plots

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] 1219+  538+  211+    9+  373    12   361+ 1345+  688   621+  427+ 3125 
##  [13]   30+  412   354+ 2184+  558   214  1091+  942+  449+ 1624  1804+  655+
##  [25]   34   476+ 2116   430+  153   129   770    31    87    12+ 1135   303+
##  [37]  784+ 1210    65  1636+ 1088  2017+  381  1450+ 3675+    8+   91    11 
##  [49]  662+  141+  474+  898+ 1168+  829+  372+  171   816+  649   303  2442+
##  [61] 2532  1823+  644+ 1295+ 1779+  555+   44+ 1241+    6+  248+  247  2728+
##  [73]  299   752    52   608+  409+  425+  810+  395+ 1731+ 1560   854+   14 
##  [85]  103   564+  314+   46   194   799+  347   724  2752+  415+ 1149   415 
##  [97]  469   643  1876+  500+  989+  552+ 1423   400+  283    36  3437+  366+
## [109]  347+  195   260+  423+  452   486+  102    65   115   819+  848+ 1633+
## [121]  765   671+  693+ 1098+  349  1351+  382+  594+  631+  480+ 1066+    0+
## [133] 1339+  322+  341+  395+   79+    0+ 1005   300  2398+  633   390+ 2028+
## [145]    1+  860+ 2131    10+ 1531+   67   698+ 3478+ 1694   344  1231+ 1363+
## [157]    6+ 1271   416  1030+  574+ 1531+  827   357+  848+  602+  272   636+
## [169]  585+  639   366   768   581   701+ 2317+ 1939+  363+  304   410    15+
## [181]  419   579+  925+    0+  458+ 1490  2301+  453+  562+  219+  728+  719+
## [193]  722+  608+  931   365  1452+   22+  879+   97  2456   697+  363+  438 
## [205] 1067+  747+ 2746+  345+  296   229+  898+  802   906+ 1970+  680+ 2301+
## [217] 1711+  327+    0+  315   601  1386  2415+  278   140  1302+  519+  910+
## [229] 1553+  640+  468+  837  1900+  555+ 1685  2513+  223  1397   359   535 
## [241]  673+    9   436+ 1229  1085+ 1372   615+ 2202+  328+  217   729+    6+
## [253]  512+ 1567+  359+ 1242+  444+  330+  478+   19  1855+  756+   21+  365+
## [265]  630+    0+ 1115+  425   170+  361+  848   412+  520+ 3308+ 2015+  555 
## [277] 2486   520+  672+  596   917+ 2324+ 2245+  262  1516+ 1791    20+  711 
## [289]  928+  780+  757  3258   899   233  1718+  308   387+  279   408+ 2102+
## [301] 1049+  101    94+  612   566+  693   556   432    NA+  399+ 1622    91 
## [313]  183+  587+ 2542   472+  406+  638+  660  2455+  137+   23+  706+  387+
## [325]  601+ 1852   627   782+  171   763+  658+ 1085+ 2412+  262   129  1495+
## [337] 1424+  547   837   570+  507+  744+  107   554+ 1562+  394   588+  575+
## [349]  180+ 1008+  951+   27   250+   56   632+ 1989+  849+  300  1145+ 1233+
## [361]   56     9+ 1618+   16   396+   20+  447+  698+ 2425+  406+  291+

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
fit = survfit(Surv(overall_survival, deceased) ~ gender, data=clin_df)

print(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(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(fit, data=clin_df, pval=T)

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(fit, data=clin_df, pval=T, risk.table=T, risk.table.col="strata")

With the risk.table=T 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"
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”):

fit = survfit(Surv(overall_survival, deceased) ~ ajcc_pathologic_stage, data=clin_df)

# we can extract the survival p-value and print it
pval = surv_pvalue(fit, data=clin_df)$pval
print(pval)
## [1] 3.081341e-06
# we produce a Kaplan-Meier plot from the fitted model
ggsurvplot(fit, data=clin_df, pval=T, risk.table=T)

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’ll see this in the next section.

5 Gene expression and survival

5.1 Overview

Ealier, 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 dataframe, 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, ]
##                 ensembl_gene_id external_gene_name original_ensembl_gene_id
## ENSG00000104938 ENSG00000104938             CLEC4M       ENSG00000104938.15
##                     logFC  AveExpr        t       P.Value     adj.P.Val
## ENSG00000104938 -9.212475 -3.23115 -45.8694 2.606088e-166 5.879855e-162
##                        B
## ENSG00000104938 368.9519
# get the ensembl gene id of the first row
gene_id = genes_df[1, "ensembl_gene_id"]

# also get the common gene name of the first row
gene_name = genes_df[1, "external_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 ENSG00000000419 ENSG00000000457
## TCGA-DD-AAD8-01A-11R-A41C-07        6.096659        4.732719        3.647218
## TCGA-O8-A75V-01A-11R-A32O-07        6.999314        4.337419        4.085811
## TCGA-CC-A9FS-01A-11R-A37K-07        9.379398        4.656832        3.534705
## TCGA-DD-AACK-01A-11R-A41C-07        6.579632        4.736928        3.412495
## TCGA-DD-A39Z-11A-21R-A213-07        7.043056        4.597276        3.768669
##                              ENSG00000000460 ENSG00000000938
## TCGA-DD-AAD8-01A-11R-A41C-07        2.181025        1.813435
## TCGA-O8-A75V-01A-11R-A32O-07        2.497387        2.204410
## TCGA-CC-A9FS-01A-11R-A37K-07        1.563299        1.461299
## TCGA-DD-AACK-01A-11R-A41C-07        2.099789        1.284629
## TCGA-DD-A39Z-11A-21R-A213-07        1.544469        2.388712
# 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] -4.923929
# 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.945619
# 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?

5.2 Exercise

Loops, plots and multiple testing

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, "ensembl_gene_id"]

    # also get the common gene name of the i-th row
    gene_name = genes_df[i, "external_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).

After you do this, you will notice that some of the p-values that were significant now are not.

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.

What is multiple testing?

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.

5.3 Exercise

You should perform clustering of tissues with liver cancer. Tip: use code similar to the one seen in gene expression data (day 3). Since, we are interested in grouping patients, you can transpose the matrix with the function t.

  • 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.


Good luck!

6 Classification (optional)

6.1 Train and test paradigm

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.

# 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.

6.2 Train Elastic Net model

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"
)

6.3 Model Evaluation

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] 22563     1
head(res_coef) # in a sparse matrix the "." represents the value of zero
## 6 x 1 sparse Matrix of class "dgCMatrix"
##                        s1
## (Intercept)     0.9443287
## ENSG00000000003 .        
## ENSG00000000419 .        
## ENSG00000000457 .        
## ENSG00000000460 .        
## ENSG00000000938 .

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) ENSG00000001617 ENSG00000024526 ENSG00000066279 ENSG00000086991 
##      0.94432866     -0.02813136     -0.02296063     -0.01138998     -0.12658976 
## ENSG00000087237 
##      0.07302113
# 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] 91
head(relevant_genes) # few select genes
## [1] "ENSG00000001617" "ENSG00000024526" "ENSG00000066279" "ENSG00000086991"
## [5] "ENSG00000087237" "ENSG00000087495"

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)
##                 ensembl_gene_id external_gene_name original_ensembl_gene_id
## ENSG00000000003 ENSG00000000003             TSPAN6       ENSG00000000003.13
## ENSG00000000419 ENSG00000000419               DPM1       ENSG00000000419.11
## ENSG00000000457 ENSG00000000457              SCYL3       ENSG00000000457.12
## ENSG00000000460 ENSG00000000460           C1orf112       ENSG00000000460.15
## ENSG00000000938 ENSG00000000938                FGR       ENSG00000000938.11
## ENSG00000000971 ENSG00000000971                CFH       ENSG00000000971.14
relevant_gene_names = limma_res$voomObj$genes[relevant_genes,"external_gene_name"]

head(relevant_gene_names) # few select genes (with readable names now)
## [1] "SEMA3F"  "DEPDC1"  "ASPM"    "NOX4"    "CETP"    "PHACTR3"

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$ensembl_gene_id, relevant_genes))
##  [1] "ENSG00000104938" "ENSG00000182566" "ENSG00000136011" "ENSG00000251049"
##  [5] "ENSG00000160323" "ENSG00000126759" "ENSG00000143369" "ENSG00000100362"
##  [9] "ENSG00000223922" "ENSG00000123454" "ENSG00000087237" "ENSG00000228842"
## [13] "ENSG00000274736" "ENSG00000250266" "ENSG00000260015" "ENSG00000226622"
## [17] "ENSG00000087495" "ENSG00000184809"

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.

6.4 Hierarchical clustering

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$ensembl_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
gene_heatmap = heatmap.2(
  t(d_mat[,relevant_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
  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 
## 46 45
# selecting just a few columns so that its easier to visualize the table
gprofiler_cols = c("significant","p.value","overlap.size","term.id","term.name")

# make sure the URL uses https
set_base_url("https://biit.cs.ut.ee/gprofiler")

# Group 1, up in tumor
gprofiler(names(clusters[clusters %in% 1]))[, gprofiler_cols]
## Warning: Please consider using the new package "gprofiler2". At the moment you are using a deprecated package relying on outdated data.
##   More information at https://biit.cs.ut.ee/gprofiler/page/r-new. Feel free to contact us at biit.support@ut.ee for further help.
##    significant  p.value overlap.size            term.id
## 1         TRUE 0.016300            7         GO:0043062
## 2         TRUE 0.014000            7         GO:0031012
## 3         TRUE 0.047500            3         GO:0030020
## 4         TRUE 0.049700            1          CORUM:254
## 5         TRUE 0.003430            6 REAC:R-HSA-1474244
## 6         TRUE 0.013200            4 REAC:R-HSA-1474228
## 7         TRUE 0.014800            3 REAC:R-HSA-1442490
## 8         TRUE 0.005780            4 REAC:R-HSA-1474290
## 9         TRUE 0.000998            4 REAC:R-HSA-2022090
## 10        TRUE 0.045100            3  REAC:R-HSA-375165
## 11        TRUE 0.019700            3 REAC:R-HSA-8948216
##                                                                  term.name
## 1                                     extracellular structure organization
## 2                                                     extracellular matrix
## 3  extracellular matrix structural constituent conferring tensile strength
## 4                                                  TBPIP/HOP2-MND1 complex
## 5                                        Extracellular matrix organization
## 6                                  Degradation of the extracellular matrix
## 7                                                     Collagen degradation
## 8                                                       Collagen formation
## 9             Assembly of collagen fibrils and other multimeric structures
## 10                                   NCAM signaling for neurite out-growth
## 11                                            Collagen chain trimerization
# Group 2, up in control
gprofiler(names(clusters[clusters %in% 2]))[, gprofiler_cols]
## Warning: Please consider using the new package "gprofiler2". At the moment you are using a deprecated package relying on outdated data.
##   More information at https://biit.cs.ut.ee/gprofiler/page/r-new. Feel free to contact us at biit.support@ut.ee for further help.
##   significant p.value overlap.size    term.id
## 1        TRUE  0.0351            7 GO:0051962
## 2        TRUE  0.0355            4 KEGG:04360
##                                           term.name
## 1 positive regulation of nervous system development
## 2                                     Axon guidance

If gprofiler does not work for you, you can also use the web interface: https://biit.cs.ut.ee/gprofiler/gost

Select g:GOSt and paste there the genes for cluster 1, and in another tab paste the genes for cluster 2, so you can compare the gene enrichment.

Feel free to explore the output result and plots, but we will not investigate it further in this course.

6.5 Exercise

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 1129

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 22562
print(dim(x_test))
## [1]   104 22562
x_train = d_mat[train_ids, ]
x_test  = d_mat[-train_ids, ]

# size after
print(dim(x_train))
## [1]  317 1129
print(dim(x_test))
## [1]  104 1129

If you don’t do this, x_train and x_test will still contain all 22534 genes, instead of only the 1127 we have selected.