## 10.12 Dates in R

### 10.12.1 Converting dates to survival time

In the melanoma example dataset, we already had the time in a convenient format for survival analysis - survival time in days since the operation. This section shows how to convert dates into “days from event”. First we will generate a dummy operation date and censoring date based on the melanoma data.

library(lubridate)
first_date = ymd("1966-01-01")           # let's create made-up dates for the operations
last_date = first_date + days(nrow(melanoma)-1) # assume tone every day from 1-Jan 1966
operation_date = seq(from = first_date, to = last_date, by = "1 day") # create dates

melanoma$operation_date = operation_date # add the created sequence to melanoma dataset # interval(anaesthetic_start_time, into_theatre_time) %>% # time_length(unit="minutes"), Now we will to create a ‘censoring’ date by adding time from the melanoma dataset to our made up operation date. Remember the censoring date is either when an event occurred (e.g. death) or the last known alive status of the patient. melanoma = melanoma %>% mutate(censoring_date = operation_date + days(time)) # (Same as doing:): melanoma$censoring_date = melanoma$operation_date + days(melanoma$time)

Now consider if we only had the operation date and censoring date. We want to create the time variable.

melanoma = melanoma %>%
mutate(time_days = censoring_date - operation_date)

The Surv() function expects a number (numeric variable), rather than a date object, so we’ll convert it:

# Surv(melanoma$time_days, melanoma$status==1) # this doesn't work
melanoma %>%
mutate(time_days_numeric = as.numeric(time_days))  ->
melanoma

#survival_object = Surv(melanoma$time_days_numeric, melanoma$status.factor == "Died") # this works as expected