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

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

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] "file_id"                   "md5sum"                   
##  [3] "file_name"                 "data_type"                
##  [5] "data_category"             "data_format"              
##  [7] "created_datetime"          "id"                       
##  [9] "updated_datetime"          "data_release"             
## [11] "submitter_id"              "version"                  
## [13] "experimental_strategy"     "access"                   
## [15] "cases"                     "state"                    
## [17] "type"                      "file_size"                
## [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] "Solid Tissue Normal" "Primary Tumor"       "Primary Tumor"

We can visualize it better with the summary function.

summary(factor(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"              "days_to_collection"         
##  [9] "sample_type"                 "state"                      
## [11] "pathology_report_uuid"       "is_ffpe"                    
## [13] "tissue_type"                 "initial_weight"             
## [15] "submitter_id"                "sample_id"                  
## [17] "oct_embedded"                "tumor_grade"                
## [19] "ajcc_pathologic_stage"       "primary_diagnosis"          
## [21] "progression_or_recurrence"   "age_at_diagnosis"           
## [23] "year_of_diagnosis"           "ajcc_pathologic_m"          
## [25] "treatments"                  "ajcc_staging_system_edition"
## [27] "tissue_or_organ_of_origin"   "diagnosis_id"               
## [29] "prior_treatment"             "site_of_resection_or_biopsy"
## [31] "days_to_diagnosis"           "morphology"                 
## [33] "tumor_stage"                 "classification_of_tumor"    
## [35] "days_to_last_follow_up"      "ajcc_pathologic_n"          
## [37] "icd_10_code"                 "last_known_disease_status"  
## [39] "ajcc_pathologic_t"           "prior_malignancy"           
## [41] "synchronous_malignancy"      "height"                     
## [43] "alcohol_history"             "exposure_id"                
## [45] "weight"                      "bmi"                        
## [47] "year_of_death"               "gender"                     
## [49] "demographic_id"              "days_to_birth"              
## [51] "race"                        "age_at_index"               
## [53] "ethnicity"                   "year_of_birth"              
## [55] "vital_status"                "days_to_death"              
## [57] "bcr_patient_barcode"         "name"                       
## [59] "disease_type"                "project_id"                 
## [61] "released"                    "primary_site"               
## [63] "releasable"                  "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$tumor_stage)
## 
## not reported      stage i     stage ii    stage iii   stage iiia   stage iiib 
##           32          189           97            6           73            8 
##   stage iiic     stage iv    stage iva    stage ivb 
##           10            3            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-AAE7-01A-11R-A41C-07 TCGA-DD-AADJ-01A-11R-A41C-07
## ENSG00000000003                         2422                         3658
## ENSG00000000005                            0                            1
## ENSG00000000419                          380                          571
## ENSG00000000457                          302                          365
## ENSG00000000460                           84                           68
## ENSG00000000938                          147                          124
##                 TCGA-UB-A7MD-01A-12R-A352-07 TCGA-BD-A2L6-11A-21R-A213-07
## ENSG00000000003                         2151                         4219
## ENSG00000000005                            4                            4
## ENSG00000000419                         1268                         1070
## ENSG00000000457                          553                          565
## ENSG00000000460                          861                          133
## ENSG00000000938                          356                         1493
##                 TCGA-CC-5259-01A-31R-A213-07 TCGA-HP-A5MZ-01A-21R-A27V-07
## ENSG00000000003                         3324                        10319
## ENSG00000000005                            1                            2
## ENSG00000000419                          341                         1137
## ENSG00000000457                          170                          687
## ENSG00000000460                           43                          226
## ENSG00000000938                           32                          382
##                 TCGA-DD-AAVS-01A-11R-A41C-07 TCGA-CC-A7IH-01A-11R-A33J-07
## ENSG00000000003                         8408                         9419
## ENSG00000000005                            0                            0
## ENSG00000000419                         1502                         1404
## ENSG00000000457                         1196                         1650
## ENSG00000000460                          436                         1585
## ENSG00000000938                          277                           81
##                 TCGA-FV-A3I0-01A-11R-A22L-07 TCGA-MI-A75H-01A-11R-A32O-07
## ENSG00000000003                        16772                         2814
## ENSG00000000005                            0                            2
## ENSG00000000419                         1422                          733
## ENSG00000000457                          662                          489
## ENSG00000000460                          164                          326
## ENSG00000000938                          190                          234
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

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

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

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

3.2 Pipeline in details (optional)

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

4 Classification

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

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

4.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                  88                   0
##   Solid Tissue Normal                   4                  12
print(paste0("Sensitivity: ",sensitivity(confusion_matrix)))
## [1] "Sensitivity: 0.956521739130435"
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"
##                          1
## (Intercept)     -0.9275012
## 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) ENSG00000024526 ENSG00000083307 ENSG00000086991 ENSG00000087237 
##    -0.927501194    -0.000375889     0.006778144    -0.080497824     0.026622104 
## ENSG00000100362 
##     0.015948993
# 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] 96
head(relevant_genes) # few select genes
## [1] "ENSG00000024526" "ENSG00000083307" "ENSG00000086991" "ENSG00000087237"
## [5] "ENSG00000100362" "ENSG00000101349"

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] "DEPDC1" "GRHL2"  "NOX4"   "CETP"   "PVALB"  "PAK5"

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" "ENSG00000136011" "ENSG00000163217" "ENSG00000251049"
##  [5] "ENSG00000160323" "ENSG00000126759" "ENSG00000164100" "ENSG00000100362"
##  [9] "ENSG00000223922" "ENSG00000126838" "ENSG00000123454" "ENSG00000087237"
## [13] "ENSG00000183166" "ENSG00000228842" "ENSG00000121207" "ENSG00000274736"
## [17] "ENSG00000260015" "ENSG00000226622" "ENSG00000107864" "ENSG00000184809"
## [21] "ENSG00000184517" "ENSG00000118972"

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.

4.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 
## 48 48
# 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               term.name
## 1        TRUE  0.0499            1 CORUM:254 TBPIP/HOP2-MND1 complex
# 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       term.name
## 1        TRUE  0.0499            1 CORUM:903 RET-Rai complex

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.

4.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)

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

5 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  64
# 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",
                      "tumor_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), tumor_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-AAE7-01A-11R-A41C-07 TCGA-DD-AAE7        Alive            NA
## TCGA-DD-AADJ-01A-11R-A41C-07 TCGA-DD-AADJ        Alive            NA
## TCGA-UB-A7MD-01A-12R-A352-07 TCGA-UB-A7MD         Dead            52
## TCGA-CC-5259-01A-31R-A213-07 TCGA-CC-5259        Alive            NA
## TCGA-HP-A5MZ-01A-21R-A27V-07 TCGA-HP-A5MZ         Dead            91
## TCGA-DD-AAVS-01A-11R-A41C-07 TCGA-DD-AAVS        Alive            NA
##                              days_to_last_follow_up      gender tumor_stage
##                                           <integer> <character> <character>
## TCGA-DD-AAE7-01A-11R-A41C-07                    644        male     stage i
## TCGA-DD-AADJ-01A-11R-A41C-07                   1066      female     stage i
## TCGA-UB-A7MD-01A-12R-A352-07                     NA        male     stage i
## TCGA-CC-5259-01A-31R-A213-07                    250      female  stage iiic
## TCGA-HP-A5MZ-01A-21R-A27V-07                     NA        male     stage i
## TCGA-DD-AAVS-01A-11R-A41C-07                   1823        male     stage i
##                               deceased overall_survival
##                              <logical>        <integer>
## TCGA-DD-AAE7-01A-11R-A41C-07     FALSE              644
## TCGA-DD-AADJ-01A-11R-A41C-07     FALSE             1066
## TCGA-UB-A7MD-01A-12R-A352-07      TRUE               52
## TCGA-CC-5259-01A-31R-A213-07     FALSE              250
## TCGA-HP-A5MZ-01A-21R-A27V-07      TRUE               91
## TCGA-DD-AAVS-01A-11R-A41C-07     FALSE             1823

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

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

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")
## Warning: Vectorized input to `element_text()` is not officially supported.
## Results may be unexpected or may change in future versions of ggplot2.

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 tumor_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$tumor_stage = gsub("[abc]$", "", clin_df$tumor_stage)

# we remove those with stage "not reported", since they are unknown
clin_df[which(clin_df$tumor_stage == "not reported"), "tumor_stage"] = NA

# finally, we also remove those with tumor stage 4, since they are too few
clin_df[which(clin_df$tumor_stage == "stage iv"), "tumor_stage"] = NA

table(clin_df$tumor_stage)
## 
##   stage i  stage ii stage iii 
##       171        86        85

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) ~ tumor_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] 1.215259e-05
# we produce a Kaplan-Meier plot from the fitted model
ggsurvplot(fit, data=clin_df, pval=T, risk.table=T)
## Warning: Vectorized input to `element_text()` is not officially supported.
## Results may be unexpected or may change in future versions of ggplot2.

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.

6 Gene expression and survival

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
expr_df = limma_res$topGenes

# print the first row, to see the gene name, the logFC value and the p-value
print(expr_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 = expr_df[1, "ensembl_gene_id"]

# also get the common gene name of the first row
gene_name = expr_df[1, "external_gene_name"]

We now have selected a gene. Let’s visualize how much differentially expressed it is:

# visualize the gene expression distribution on the diseased samples (in black)
# versus the healthy samples (in red)
expr_diseased = d_mat[rownames(clin_df), gene_id]
expr_healthy = d_mat[setdiff(rownames(d_mat), 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 = d_mat[rownames(clin_df), gene_id]

# find the median value of the gene and print it
median_value = median(clin_df$gene_value)
print(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
print(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))
## Warning: Vectorized input to `element_text()` is not officially supported.
## Results may be unexpected or may change in future versions of ggplot2.

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?

6.1 Exercise

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.

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.