library(survival)
library(readxl)

#Change according to your data path

data1 <- read_excel("E:/UCSI/MyNotes/AS305 Survival Analysis/Chapter 3/data1.xlsx")
View(data1)

#Example 1

tt <- c(7,6,6,5,2,4)
cens <- c(0,1,0,0,1,1)
Surv(tt, cens)
## [1] 7+ 6  6+ 5+ 2  4
result.km <- survfit(Surv(tt, cens) ~ 1, conf.type="log-log")
summary(result.km)
## Call: survfit(formula = Surv(tt, cens) ~ 1, conf.type = "log-log")
## 
##  time n.risk n.event survival std.err lower 95% CI upper 95% CI
##     2      6       1    0.833   0.152       0.2731        0.975
##     4      5       1    0.667   0.192       0.1946        0.904
##     6      3       1    0.444   0.222       0.0662        0.785
plot(result.km)

result.fh<-survfit(Surv(tt,cens)~1, conf.type="log-log", type="fh")
summary(result.fh)
## Call: survfit(formula = Surv(tt, cens) ~ 1, conf.type = "log-log", 
##     type = "fh")
## 
##  time n.risk n.event survival std.err lower 95% CI upper 95% CI
##     2      6       1    0.846   0.141        0.306        0.977
##     4      5       1    0.693   0.180        0.229        0.913
##     6      3       1    0.497   0.210        0.101        0.807

#Remark: #survfit: This is a function from the “survival” package in R used for fitting survival curves.

#Surv(tt, cens) ~ 1: This specifies the survival formula. In this case, it’s a simple survival formula with tt representing the survival times and cens representing censoring information. The ~ 1 part indicates that we are fitting a survival curve without considering any specific covariates.

#conf.type = “log-log”: This argument specifies the type of confidence intervals to be computed. In this case, it’s set to “log-log,” which is one of the methods for calculating confidence intervals in survival analysis.

#type = “fh”: This argument specifies the type of survival curve to be computed. In this case, it’s set to “fh,” which stands for Fleming-Harrington. The Fleming-Harrington estimator is used to emphasize early differences in survival curves.

#Example

# Sample data (replace with your own data)
data_group1 <- c(10, 15, 20, 25, 30, 35, 40, 45)
data_group2 <- c(5, 10, 15, 20, 25, 30, 35)

# Create survival objects for each group
surv_obj_group1 <- Surv(data_group1)
surv_obj_group2 <- Surv(data_group2)

# Fit Kaplan-Meier survival curves
fit_group1 <- survfit(surv_obj_group1 ~ 1, data = data.frame(time = data_group1))
fit_group2 <- survfit(surv_obj_group2 ~ 1, data = data.frame(time = data_group2))

# Plot Kaplan-Meier curves
plot(fit_group1, col = "blue", lty = 1, main = "Kaplan-Meier Curves for Group 1 and Group 2")
lines(fit_group2, col = "red", lty = 2)

# Add legend
legend("topright", legend = c("Group 1", "Group 2"), col = c("blue", "red"), lty = 1:2)

# Add labels
xlabel <- "Time"
ylabel <- "Survival Probability"
title(main = "Kaplan-Meier Curves for Group 1 and Group 2", xlab = xlabel, ylab = ylabel)

#Example 3

tt <- c(6,6,6,6,7, 9, 10, 10, 11, 13, 16, 17, 19, 20, 22, 23, 25, 32, 32, 34, 35)
cens <- c(1,1,1,0,1,0,1,0,0,1,1,0,0,0,1,1,0,0,0,0,0)
dataG1<-Surv(tt, cens)

result1<-survfit(dataG1 ~ 1, conf.type="log-log")
summary(result1)
## Call: survfit(formula = dataG1 ~ 1, conf.type = "log-log")
## 
##  time n.risk n.event survival std.err lower 95% CI upper 95% CI
##     6     21       3    0.857  0.0764        0.620        0.952
##     7     17       1    0.807  0.0869        0.563        0.923
##    10     15       1    0.753  0.0963        0.503        0.889
##    13     12       1    0.690  0.1068        0.432        0.849
##    16     11       1    0.627  0.1141        0.368        0.805
##    22      7       1    0.538  0.1282        0.268        0.747
##    23      6       1    0.448  0.1346        0.188        0.680
tt2 <- c(1,1,2,2,3,4,4,5,5,8,8,8,8,11,11,12,12,15,17,22,23)
cens2 <- c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
dataG2<-Surv(tt2, cens2)

result2<-survfit(dataG2 ~ 1, conf.type="log-log")
summary(result2)
## Call: survfit(formula = dataG2 ~ 1, conf.type = "log-log")
## 
##  time n.risk n.event survival std.err lower 95% CI upper 95% CI
##     1     21       2   0.9048  0.0641      0.67005        0.975
##     2     19       2   0.8095  0.0857      0.56891        0.924
##     3     17       1   0.7619  0.0929      0.51939        0.893
##     4     16       2   0.6667  0.1029      0.42535        0.825
##     5     14       2   0.5714  0.1080      0.33798        0.749
##     8     12       4   0.3810  0.1060      0.18307        0.578
##    11      8       2   0.2857  0.0986      0.11656        0.482
##    12      6       2   0.1905  0.0857      0.05948        0.377
##    15      4       1   0.1429  0.0764      0.03566        0.321
##    17      3       1   0.0952  0.0641      0.01626        0.261
##    22      2       1   0.0476  0.0465      0.00332        0.197
##    23      1       1   0.0000     NaN           NA           NA
plot(result1, col = "blue", lty = 1, main = "Kaplan-Meier Curves for with treatment and placebo")
lines(result2, col = "red", lty = 1)

#plot(result)

#Example 4: smoking

group<-as.factor(data1$Group)
status<-as.factor(data1$status)
day<-as.factor(data1$day)
data1
surv.object <- with(data1, Surv(day,status))
surv.object
##  [1]   4+   7    8+  29+  29   31+  40   65   69   78+  79+ 106  107+ 129  130+
## [16] 140+ 142+ 149  158+ 160  161  162+ 187  188+ 197  204+ 208+ 221  228  231+
fit<-survival::survfit(Surv(day,status) ~ Group, data=data1)

fit<-survival::survfit(surv.object ~ Group, data=data1)

summary(fit)
## Call: survfit(formula = surv.object ~ Group, data = data1)
## 
##                 Group=1 
##  time n.risk n.event survival std.err lower 95% CI upper 95% CI
##     7     16       1    0.938  0.0605        0.826        1.000
##    29     14       1    0.871  0.0856        0.718        1.000
##    65     12       1    0.798  0.1048        0.617        1.000
##   149      7       1    0.684  0.1386        0.460        1.000
##   160      5       1    0.547  0.1651        0.303        0.989
##   187      3       1    0.365  0.1852        0.135        0.987
##   221      1       1    0.000     NaN           NA           NA
## 
##                 Group=2 
##  time n.risk n.event survival std.err lower 95% CI upper 95% CI
##    40     12       1    0.917  0.0798       0.7729        1.000
##    69     11       1    0.833  0.1076       0.6470        1.000
##   106      8       1    0.729  0.1355       0.5066        1.000
##   129      7       1    0.625  0.1510       0.3893        1.000
##   161      6       1    0.521  0.1577       0.2877        0.943
##   197      5       1    0.417  0.1568       0.1993        0.871
##   228      2       1    0.208  0.1669       0.0433        1.000
plot(fit, xlab="Survival Time in Days", ylab="% Surviving", yscale=100, col=c("red", "blue"), main="Survival distribution by group") 
legend("topright", title="Group", c("smokers", "non-smokers"), fill = c("red", "blue"))

#Example 5: Generating survival data

# Set a seed for reproducibility
set.seed(123)

# Number of observations
n <- 100

# Generate covariate data (optional)
covariate_data <- data.frame(
  age = rnorm(n, mean = 50, sd = 10),
  sex = sample(c("Male", "Female"), size = n, replace = TRUE)
)

# Generate survival times
survival_times <- rexp(n, rate = 0.02)  # Exponential distribution with a hazard rate of 0.02

# Generate censoring indicator (0 for event, 1 for censored)
censoring_indicator <- rbinom(n, size = 1, prob = 0.2) 

# Combine survival times and censoring indicator into a survival object
survival_data <- Surv(time = survival_times, event = 1 - censoring_indicator)

# Combine covariate data and survival data into a dataframe
survival_df <- data.frame(survival_data, covariate_data)

# Display the first few rows of the dataset
head(survival_df)
survival_df

#Example 6: Lung data

# install.packages(c("lubridate", "ggsurvfit", "gtsummary", "tidycmprsk"))
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(ggsurvfit)
## Loading required package: ggplot2
library(gtsummary)
## #StandWithUkraine
library(tidycmprsk)
## 
## Attaching package: 'tidycmprsk'
## The following object is masked from 'package:gtsummary':
## 
##     trial
# devtools::install_github("zabore/condsurv")
library(condSURV)
## Warning in .recacheSubclasses(def@className, def, env): undefined subclass
## "ndiMatrix" of class "replValueSp"; definition not updated
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
lung <- 
  lung %>% 
  mutate(
    status = recode(status, `1` = 0, `2` = 1)
  )
head(lung[, c("time", "status", "sex")])
Surv(lung$time, lung$status)[1:10]
##  [1]  306   455  1010+  210   883  1022+  310   361   218   166
s1 <- survfit(Surv(time, status) ~ 1, data = lung)
str(s1)
## List of 16
##  $ n        : int 228
##  $ time     : num [1:186] 5 11 12 13 15 26 30 31 53 54 ...
##  $ n.risk   : num [1:186] 228 227 224 223 221 220 219 218 217 215 ...
##  $ n.event  : num [1:186] 1 3 1 2 1 1 1 1 2 1 ...
##  $ n.censor : num [1:186] 0 0 0 0 0 0 0 0 0 0 ...
##  $ surv     : num [1:186] 0.996 0.982 0.978 0.969 0.965 ...
##  $ std.err  : num [1:186] 0.0044 0.00885 0.00992 0.01179 0.01263 ...
##  $ cumhaz   : num [1:186] 0.00439 0.0176 0.02207 0.03103 0.03556 ...
##  $ std.chaz : num [1:186] 0.00439 0.0088 0.00987 0.01173 0.01257 ...
##  $ type     : chr "right"
##  $ logse    : logi TRUE
##  $ conf.int : num 0.95
##  $ conf.type: chr "log"
##  $ lower    : num [1:186] 0.987 0.966 0.959 0.947 0.941 ...
##  $ upper    : num [1:186] 1 1 0.997 0.992 0.989 ...
##  $ call     : language survfit(formula = Surv(time, status) ~ 1, data = lung)
##  - attr(*, "class")= chr "survfit"
survfit2(Surv(time, status) ~ 1, data = lung) %>% 
  ggsurvfit() +
  labs(
    x = "Days",
    y = "Overall survival probability"
  )

survfit2(Surv(time, status) ~ 1, data = lung) %>% 
  ggsurvfit() +
  labs(
    x = "Days",
    y = "Overall survival probability"
  ) + 
  add_confidence_interval()

survfit2(Surv(time, status) ~ 1, data = lung) %>% 
  ggsurvfit() +
  labs(
    x = "Days",
    y = "Overall survival probability"
    ) + 
  add_confidence_interval() +
  add_risktable()

#Example 7: Estimating x years of survival

summary(survfit(Surv(time, status) ~ 1, data = lung), times = 365.25)
## Call: survfit(formula = Surv(time, status) ~ 1, data = lung)
## 
##  time n.risk n.event survival std.err lower 95% CI upper 95% CI
##   365     65     121    0.409  0.0358        0.345        0.486
survfit(Surv(time, status) ~ 1, data = lung) %>% 
  tbl_survfit(
    times = 365.25,
    label_header = "**1-year survival (95% CI)**"
  )
Characteristic 1-year survival (95% CI)
Overall 41% (34%, 49%)

#Example 8: Estimating median survival time

survfit(Surv(time, status) ~ 1, data = lung)
## Call: survfit(formula = Surv(time, status) ~ 1, data = lung)
## 
##        n events median 0.95LCL 0.95UCL
## [1,] 228    165    310     285     363