The Wayback Machine - https://web.archive.org/web/20240927060622/https://www.geeksforgeeks.org/survival-analysis-in-r/
Open In App

Survival Analysis in R

Last Updated : 13 Dec, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Survival analysis in R Programming Language deals with the prediction of events at a specified time. It deals with the occurrence of an interesting event within a specified time and failure of it produces censored observations i.e incomplete observations. 

Survival analysis in R Programming Language

Biological sciences are the most important application of survival analysis in which we can predict the time for organisms eg. when they will multiply to sizes etc.

Methods used to do survival analysis: 

There are two methods that can be used to perform survival analysis in R programming language: 

  • Kaplan-Meier method
  • Cox Proportional hazard model

Kaplan-Meier Method

The Kaplan-Meier method is used in survival distribution using the Kaplan-Meier estimator for truncated or censored data. It’s a non-parametric statistic that allows us to estimate the survival function and thus not based on underlying probability distribution. The Kaplan–Meier estimates are based on the number of patients (each patient as a row of data) from the total number of patients who survive for a certain time after treatment. (which is the event). 

We represent the Kaplan–Meier function by the formula: 

Here S(t) represents the probability that life is longer than t with ti(At least one event happened), di represents the number of events(e.g. deaths) that happened in time ti and ni represents the number of individuals who survived up to time ti.

Example: 

We will use the Survival package for the analysis. Using Lung dataset preloaded in survival package which contains data of 228 patients with advanced lung cancer from North Central cancer treatment group based on 10 features. The dataset contains missing values so, missing value treatment is presumed to be done at your side before the building model. 

R




# Installing package
install.packages("survival")
 
# Loading package
library(survival)
 
# Dataset information
?lung
 
# Fitting the survival model
Survival_Function = survfit(Surv(lung$time,
                                 lung$status == 2)~1)
Survival_Function
 
# Plotting the function
plot(Survival_Function)


Here, we are interested in “time” and “status” as they play an important role in the analysis. Time represents the survival time of patients. Since patients survive, we will consider their status as dead or non-dead(censored). 

The Surv() function takes two times and status as input and creates an object which serves as the input of survfir() function. We pass ~1 in survfit() function to ensure that we are telling the function to fit the model on basis of the survival object and have an interrupt.

survfit() creates survival curves and prints the number of values, number of events(people suffering from cancer), the median time and 95% confidence interval. The plot gives the following output: 

Here, the x-axis specifies “Number of days” and the y-axis specifies the “probability of survival“. The dashed lines are upper confidence interval and lower confidence interval. 

We also have the confidence interval which shows the margin of error expected i.e In days of surviving 200 days, upper confidence interval reaches 0.76 or 76% and then goes down to 0.60 or 60%. 

Cox proportional hazard model

It is a regression modeling that measures the instantaneous risk of deaths and is bit more difficult to illustrate than the Kaplan-Meier estimator. It consists of hazard function h(t) which describes the probability of event or hazard h(e.g. survival) up to a particular time t. Hazard function considers covariates(independent variables in regression) to compare the survival of patient groups. 
It does not assume an underlying probability distribution but it assumes that the hazards of the patient groups we compare are constant over time and because of this it is known as “Proportional hazard model“. 

Example: 

We will use the Survival package for the analysis. Using Lung dataset preloaded in survival package which contains data of 228 patients with advanced lung cancer from North Central cancer treatment group based on 10 features. The dataset contains missing values so, missing value treatment is presumed to be done at your side before the building model. We will be using the cox proportional hazard function coxph() to build the model. 

R




# Installing package
install.packages("survival")
 
# Loading package
library(survival)
 
# Dataset information
?lung
 
# Fitting the Cox model
Cox_mod <- coxph(Surv(lung$time,
                      lung$status == 2)~., data = lung)
 
# Summarizing the model
summary(Cox_mod)
 
# Fitting survfit()
Cox <- survfit(Cox_mod)
 
# Plotting the function
plot(Cox)


Here, we are interested in “time” and “status” as they play an important role in the analysis. Time represents the survival time of patients. Since patients survive, we will consider their status as dead or non-dead(censored). 

The Surv() function takes two times and status as input and creates an object which serves as the input of survfir() function. We pass ~1 in survfit() function to ensure that we are telling the function to fit the model on basis of the survival object and have an interrupt.

The Cox_mod output is similar to the regression model. There are some important features like age, sex, ph.ecog and wt. loss. The plot gives the following output: 

Here, the x-axis specifies “Number of days” and the y-axis specifies “probability of survival“. The dashed lines are upper confidence interval and lower confidence interval. In comparison with the Kaplan-Meier plot, the Cox plot is high for initial values and lower for higher values because of more variables in the Cox plot.

We also have the confidence interval which shows the margin of error expected i.e In days of surviving 200 days, the upper confidence interval reaches 0.82 or 82% and then goes down to 0.70 or 70%.

Note: Cox model serves better results than Kaplan-Meier as it is most volatile with data and features. Cox model is also higher for lower values and vice-versa i.e drops down sharply when the time increases.



Similar Reads

Single-Table Analysis with dplyr using R Language
The dplyr package is used to perform simulations in the data by performing manipulations and transformations. It can be installed into the working space using the following command : install.packages("dplyr") Let's create the main dataframe: C/C++ Code #installing the required libraries library(dplyr) #creating a data frame data_frame = data.frame(
5 min read
Principal Component Analysis with R Programming
Principal component analysis(PCA) in R programming is an analysis of the linear components of all existing attributes. Principal components are linear combinations (orthogonal transformation) of the original predictor in the dataset. It is a useful technique for EDA(Exploratory data analysis) and allows you to better visualize the variations presen
3 min read
Social Network Analysis Using R Programming
Social Network Analysis (SNA) is the process of exploring or examining the social structure by using graph theory. It is used for measuring and analyzing the structural properties of the network. It helps to measure relationships and flows between groups, organizations, and other connected entities. Before we start let us see some network analysis
6 min read
Predictive Analysis in R Programming
Predictive analysis in R Language is a branch of analysis which uses statistics operations to analyze historical facts to make predict future events. It is a common term used in data mining and machine learning. Methods like time series analysis, non-linear least square, etc. are used in predictive analysis. Using predictive analytics can help many
4 min read
Performing Analysis of a Factor in R Programming - factanal() Function
Factor Analysis also known as Exploratory Factor Analysis is a statistical technique used in R programming to identify the inactive relational structure and further, narrowing down a pool of variables to few variables. The main motive to use this technique is to find out which factor is most responsible for influence in the categorization of weight
2 min read
Regression Analysis in R Programming
In statistics, Logistic Regression is a model that takes response variables (dependent variable) and features (independent variables) to determine the estimated probability of an event. A logistic model is used when the response variable has categorical values such as 0 or 1. For example, a student will pass/fail, a mail is a spam or not, determini
6 min read
Perform Probability Density Analysis on t-Distribution in R Programming - dt() Function
dt() function in R Language is used to return the probability density analysis on the Student t-distribution with random variable x and degree of freedom df. Syntax: dt(x, df) Parameters: x: Random Variable df: Degree of Freedom Example 1: # R Program to perform # Probability Density Analysis # Calling dt() Function dt(0, 10) dt(1, 15) dt(3, 40) Ou
1 min read
Perform the Probability Cumulative Density Analysis on t-Distribution in R Programming - pt() Function
pt() function in R Language is used to return the probability cumulative density of the Student t-distribution. Syntax: pt(x, df) Parameters: x: Random variable df: Degree of Freedom Example 1: # R Program to perform # Cumulative Density Analysis # Calling pt() Function pt(2, 10) pt(.542, 15) Output: [1] 0.963306 [1] 0.7021105 Example 2: # R Progra
1 min read
Perform the Inverse Probability Cumulative Density Analysis on t-Distribution in R Programming - qt() Function
qt() function in R Language is used to return the inverse probability cumulative density of the Student t-distribution. Syntax: qt(x, df)Parameters: x: Random variable df: Degree of Freedom Example 1: C/C++ Code # R Program to perform Inverse # Cumulative Density Analysis # Calling qt() Function qt(.95, 10) qt(.542, 15) Output: [1] 1.812461 [1] 0.1
1 min read
Perform Linear Regression Analysis in R Programming - lm() Function
lm() function in R Language is a linear model function, used for linear regression analysis. Syntax: lm(formula) Parameters: formula: model description, such as x ~ y Example 1: # R program to illustrate # lm function # Creating two vectors x and y x <- c(rep(1:20)) y <- x * 2 # Calling lm() function to # fit a linear model f <- lm(x ~ y)
1 min read
Linear Discriminant Analysis in R Programming
One of the most popular or well established Machine Learning technique is Linear Discriminant Analysis (LDA ). It is mainly used to solve classification problems rather than supervised classification problems. It is basically a dimensionality reduction technique. Using the Linear combinations of predictors, LDA tries to predict the class of the giv
6 min read
Time Series Analysis using ARIMA model in R Programming
In R programming, data analysis and visualization is so easy to learn the behaviour of the data. Moreover, the R language is used mostly in the data science field after Python. Time series analysis is a type of analysis of data used to check the behaviour of data over a period of time. The data is collected over time sequentially by the ts() functi
6 min read
Time Series Analysis using Facebook Prophet in R Programming
Time Series Analysis is a way of analysing and learning the behaviour of datasets over a period. Moreover, it helps in learning the behavior of the dataset by plotting the time series object on the graph. In R programming, it can be easily performed by using ts() function that takes the data vector and converts it into time series object as specifi
3 min read
Relative Importance Analysis in R
A statistical method called relative importance analysis (RIA) is used to assess the relative contribution of independent variables to the variance of a dependent variable. It is used to evaluate the relative weights of predictor variables in a model. It enables us to recognize the predictors that are most crucial in illuminating the variation in t
4 min read
How to Perform Hierarchical Cluster Analysis using R Programming?
Cluster analysis or clustering is a technique to find subgroups of data points within a data set. The data points belonging to the same subgroup have similar features or properties. Clustering is an unsupervised machine learning approach and has a wide variety of applications such as market research, pattern recognition, recommendation systems, and
5 min read
Quadratic Discriminant Analysis
Linear Discriminant Analysis Now, Let's consider a classification problem represented by a Bayes Probability distribution P(Y=k | X=x), LDA does it differently by trying to model the distribution of X given the predictors class (I.e. the value of Y) P(X=x| Y=k): [Tex]P(Y=k | X=x) = \frac{P(X=x | Y=k) P(Y=k)}{P(X=x)}[/Tex] [Tex]= \frac{P(X=x | Y=k)
4 min read
How to Perform Univariate Analysis in R?
In this article, we will discuss how to perform Univariate Analysis in R Programming Language. Univariate Analysis means doing an Analysis of one variable. The analysis of univariate data is thus the simplest form of analysis since the information deals with only one quantity that changes. Example: R program to create a vector with 10 elements and
3 min read
Multivariate Analysis in R
Analyzing data sets with numerous variables is a crucial statistical technique known as multivariate analysis. Many different multivariate analysis procedures can be carried out using the well-liked programming language R. A number of libraries and functions are available in the well-liked programming language R for carrying out multivariate analys
8 min read
GE Stock Price Analysis Using R Language
Stock analysis is a technique used by investors and traders to make purchasing and selling choices. Investors and traders strive to obtain an advantage in the markets by making educated judgments by researching and analyzing previous and current data. In this article, we will analyze the 'GE Stock Price' dataset using the R Programming Language. Th
5 min read
Outlier Analysis in R
This article will focus on the outlier analysis, including Outlier detection and removal in the R programming language. What are outliers? Data points far from the dataset's other points are considered outliers. This refers to the data values dispersed among other data values and upsetting the dataset's general distribution.Outlier detection is a s
4 min read
SQL vs R - Which to use for Data Analysis?
Data Analysis, as the name suggests, means the evaluation or examination of the data, in Layman’s terms. The answer to the question as to why Data Analysis is important lies in the fact that deriving insights from the data and understanding them are extremely crucial for organizations and businesses across the globe for profits. Data Analysis essen
5 min read
Correspondence Analysis Using R
Correspondence Analysis is a dimension reduction technique used to summarize large contingency tables into a smaller number of dimensions, allowing you to visualize the relationships between categories. The technique is based on singular value decomposition, and it results in a scatterplot that shows the relationships between categories in a 2-dime
6 min read
Discriminant Function Analysis Using R
Discriminant Function Analysis (DFA) is a statistical method used to find a discriminant function that can separate two or more groups based on their independent variables. In other words, DFA is used to determine which variables contribute most to group separation. DFA is a helpful tool in various fields such as finance, biology, marketing, etc. I
6 min read
Graphical Data Analysis in R
Graphical Data Analysis (GDA) is a powerful tool that helps us to visualize and explore complex data sets. R is a popular programming language for GDA as it has a wide range of built-in functions for producing high-quality visualizations. In this article, we will explore some of the most commonly used GDA techniques in the R Programming Language. F
7 min read
Factor Analysis in R programming
Factor Analysis (FA) is a statistical method that is used to analyze the underlying structure of a set of variables. It is a method of data reduction that seeks to explain the correlations among many variables in terms of a smaller number of unobservable (latent) variables, known as factors. In R Programming Language, the psych package provides a v
10 min read
How to perform a meta-analysis with R
Meta-analysis is a sophisticated statistical technique combining and analyzing data from multiple independent studies to obtain a more comprehensive and reliable estimate of the relationship or effect size between variables. It provides a means of systematically reviewing and synthesizing findings from individual studies to derive more robust concl
15 min read
Redundancy Analysis using R
A Redundancy Analysis (RDA) is a multivariate statistical technique used to explore the relationship between two sets of variables: response variables and predictor variables. It is commonly used in ecological and environmental research to understand the influence of predictor variables on the variation in response variables. The main purpose of RD
5 min read
Stock Data Analysis and Data Visualization with Quantmod in R
Analysis of historical stock price and volume data is done in order to obtain knowledge, make wise decisions, and create trading or investment strategies. The following elements are frequently included in the examination of stock data in the R Programming Language. Historical Price Data: Historical price data contains information about a stock's op
8 min read
Geospatial Data Analysis with R
Geospatial data analysis involves working with data that has a geographic or spatial component. It allows us to analyze and visualize data in the context of its location on the Earth's surface. R Programming Language is a popular open-source programming language, that offers a wide range of packages and tools for geospatial data analysis. fundament
5 min read
Time Series Analysis in R
Time Series Analysis in R is used to see how an object behaves over some time. In R Programming Language, it can be easily done by the ts() function with some parameters. Time series takes the data vector and each data is connected with a timestamp value as given by the user. in R time series analysis this function is mostly used to learn and forec
5 min read