0% found this document useful (0 votes)
7 views5 pages

Kaplan-Meier Survival Analysis in R

Uploaded by

tahmidnesam789
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views5 pages

Kaplan-Meier Survival Analysis in R

Uploaded by

tahmidnesam789
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

##Kaplan-Maier function

km<-function(time,status){
n<-length(time)
[Link]<-order(time)
risk<-n:1
pi<-(risk-status)/risk
est<-vector("numeric",n)
sest<-vector("numeric",n)
for(i in 1:n){est[i]<-prod(pi[1:i])
sest[i]<-sqrt(est[i]*est[i]*sum(1/(risk[1:i]*(risk[1:i]-1))))
}
result<-list(stime=time,even=status,risk=risk,kmest=est,Greenwood=sest) #result
df <- [Link](Result = result)
print(df)
}

##Application to lung data


library(survival)
lung
km(lung$time,lung$status)

##Application to stanford2 data


stanford2
km(stanford2$time,stanford2$status)

##Appilcation to ovarian data


ovarian
km(ovarian$futime,ovarian$fustat)

##Application to leukemia data


leukemia
km(leukemia$time,leukemia$status)
###kaplan-Maier estimation using built-in function in survival package(stanford2 data)

library(survival)
(stanford2)

#Create a survival object


surv_obj <- Surv(time = stanford2$time, event = stanford2$status)

# Compute the Kaplan–Meier estimate using survfit


km_fit <- survfit(surv_obj ~ 1) # No grouping

# View summary of the fit


summary(km_fit)

# Plot the Kaplan–Meier survival curve


plot(km_fit, xlab = "Time", ylab = "Survival Probability", main = "Kaplan–Meier Curve", col = "blue", lwd =
2)
grid()

# If you want to get survival probability at time = 228


surv_at_228 <- summary(km_fit, times = 228)
print(surv_at_228)

###kaplan-Maier estimation using built-in function in survival package(lung data)

library(survival)
(lung)

#Create a survival object


[Link] <- Surv(time = lung$time, event = lung$status)

# Compute the Kaplan–Meier estimate using survfit


[Link] <- survfit([Link] ~ 1) # No grouping

# View summary of the fit


summary([Link])

# Plot the Kaplan–Meier survival curve


plot([Link], xlab = "Time", ylab = "Survival Probability", main = "Kaplan–Meier Curve", col = "blue", lwd =
2)
grid()
# If you want to get survival probability at time = 200
surv_at_200 <- summary([Link], times = 200)
print(surv_at_200)

##performing log rank test to test about survival difference

#Null hypothesis: there is no difference in survival between males and females.


fit_sex <- survdiff([Link] ~ sex, data = lung)
fit_sex
km_sex <- survfit(Surv(time, status) ~ sex, data = lung)
plot(km_sex, col = c("blue", "red"), lwd = 2,
xlab = "Time", ylab = "Survival Probability",
main = "Survival Curves by Sex")
legend("topright", legend = c("Male", "Female"),
col = c("blue", "red"), lwd = 2)

###Fitting of exponential survival model

s2 <- survreg(Surv(time, status) ~ 1, data = lung, dist = "exponential")


summary(s2)

#Extracting the rate parameter


lamda <- exp(-6.0445)
lamda

# Generate time values for plotting


t_seq <- seq(0, max(lung$time, [Link] = TRUE), [Link] = 200)

# Compute Survival Function (S(t)) for Exponential model


S_t <- exp(-lamda * t_seq)

# Compute CDF (F(t)) for Exponential model


F_t <- 1 - exp(-lamda * t_seq)

# Plot Survival Function and CDF on the same graph


par(mfrow = c(1, 2)) # Set up 2 plots side by side

# Plot Survival Function


plot(t_seq, S_t,
type = "l", col = "blue", lwd = 2,
xlab = "Time", ylab = "Survival Probability",
main = "Exponential Survival Function")
grid()

# Plot CDF
plot(t_seq, F_t,
type = "l", col = "red", lwd = 2,
xlab = "Time", ylab = "Cumulative Probability",
main = "Exponential CDF")
grid()

par(mfrow = c(1, 1)) # Reset to single plot

###Fitting of Weibull survival model

# Fit Weibull model with default behavior (scale is estimated)


s3 <- survreg(Surv(time, status) ~ 1, data = lung, dist = "weibull")

# Show summary
summary(s3)

scale_survreg <- 0.759 # scale output from survreg


intercept <- 6.0349 # intercept output from survreg

# Compute Weibull shape


lambda <- 1 / scale_survreg # shape parameter (λ)
lambda

# Compute alpha using: alpha = exp(-λ * intercept)


alpha <- exp(-lambda * intercept)
alpha

#Generate a sequence of time points


t_seq <- seq(1, max(lung$time, [Link] = TRUE), [Link] = 200)

# Compute Weibull survival


S_t <- exp(-alpha * t_seq^lambda)

# Plot Weibull survival function


plot(t_seq, S_t,
type = "l",
col = "red",
lwd = 2,
xlab = "Time",
ylab = "Survival Probability",
main = "Weibull Survival Curve")
grid()

# Calculate Weibull CDF at each time point


F_t <- 1 - exp(-alpha * t_seq^lambda)

# Plot the CDF


plot(t_seq, F_t,
type = "l",
col = "blue",
lwd = 2,
xlab = "Time",
ylab = "Cumulative Probability",
main = "CDF of Weibull Model (Lung Data)")
grid()

##Negative binomial regression to epil dataset

# Load the MASS package


library(MASS)

# Load the epil dataset


data(epil)

# View the first few rows of the epil dataset


head(epil)

# Fit a negative binomial regression model


model_nb <- [Link](y ~ base+trt + age, data = epil)

# Summarize the model


summary(model_nb)

Common questions

Powered by AI

The computational approach for generating survival functions in exponential and Weibull models involves the use of the `survreg` function to fit the respective models, extracting estimated parameters such as the intercept and scale, and employing these in mathematical formulations. For the exponential model, the survival function is calculated as S(t) = exp(-lambda * t), whereas for the Weibull model, S(t) is computed as exp(-alpha * t^lambda). Cumulative distribution functions are determined by subtracting the survival probability from one. These computations are executed over a sequence of time points, allowing for visualization and interpretation of survival dynamics .

Weibull model fitting in survival analysis involves using the `survreg` function to fit a model to survival data, specifying the Weibull distribution. The process derives key parameters such as the model intercept and scale. The shape parameter (λ) dictates the hazard rate's behavior, indicating whether it increases, decreases, or remains constant over time, while the scale parameter influences the overall distribution of survival times. A large scale parameter broadens the curve, indicating higher variability in survival times. This fitting provides insights into the underlying survival dynamics specific to the dataset, such as those from the lung data .

The exponential model assumes a constant hazard rate and is characterized by a rate parameter, estimated from the data. It simplifies the survival function as an exponential decay over time. In contrast, the Weibull model accounts for varying hazard rates with its two parameters: scale and shape. The Weibull function is more versatile as it can model increasing or decreasing hazard rates, making it suitable for more complex survival data. Application involves fitting the model to data, such as using the `survreg` function, and plotting survival and cumulative distribution functions to interpret the survival probabilities over time .

Greenwood's formula assists in the interpretation of Kaplan-Meier estimates by providing a way to estimate the variance of the survival probability at different time points. It computes the variance based on the cumulative product of the proportion of subjects at risk minus the event status, divided by the risk squared at each time point. This variance estimation is crucial for constructing confidence intervals around the survival estimates, enabling an understanding of the precision and reliability of the Kaplan-Meier survival estimates .

The log-rank test compares survival curves by fitting a survival model, such as the Kaplan-Meier estimator, to the data grouped by a categorical variable (e.g., sex). The survival differences are tested using `survdiff`, which examines if there is a statistically significant difference between groups. The null hypothesis being tested is that there is no difference in survival between groups, such as males and females in the lung data set .

The Kaplan-Meier estimator is constructed by ordering the event times, determining the number of subjects at risk at each event time, and calculating survival probabilities. It is applied by using data sets such as lung, stanford2, ovarian, and leukemia, where the survival object is created using time and event status, followed by computing the estimator with the `survfit` function. This computation involves plotting survival curves and obtaining probabilities at specified times .

Survival probabilities in Kaplan-Meier analysis are represented through survival curves that plot time on the x-axis and survival probability on the y-axis. These graphs display the stepwise decline in survival probability at each event time. Key insights include identifying the median survival time, comparing survival over multiple groups, and highlighting periods with high or low hazard rates. These graphical tools are critical for visually assessing the pattern of survival in the data, such as different groups in the lung data set .

In the Weibull survival model, lambda (λ) is the shape parameter determining the hazard function's behavior, while alpha (α) is a scale parameter influencing the survival curve's scale. Lambda is computed as the reciprocal of the scale parameter obtained from `survreg`, while alpha is derived by exponentiating the product of negative lambda and the model intercept. These parameters are estimated using maximum likelihood estimation and facilitate the construction of the survival function to model varying hazard rates over time .

Negative binomial regression is applied to the epil dataset to model count data where variance exceeds the mean, as opposed to Poisson regression which assumes equal mean and variance. It accounts for overdispersion effectively. The model includes variables such as baseline seizure count (base), treatment indicator (trt), and age, allowing for the analysis of factors influencing seizure counts in epilepsy patients. This choice of variables helps in understanding and predicting patterns in the data while accommodating the overdispersed nature of the counts .

The exponential survival model assumes a constant hazard rate over time, characterized by a single parameter, the rate (lambda), making it simpler but less flexible than the Kaplan-Meier estimator, which is non-parametric and does not rely on assumptions about the distribution or shape of the hazard function. In the exponential model, the rate parameter is estimated using maximum likelihood methods, whereas the Kaplan-Meier approach empirically estimates survival probabilities without assuming a constant hazard .

You might also like