Search code examples
rsurvival-analysissurvival

How to create a co-variate time dependent to use in `coxph` model in survival package in r?


I have a data set like this:

  id       status  time event   
  <chr>     <dbl> <dbl> <time>  
1 22016890      1   459 425 days
2 22042190      1    83  NA days
3 18108887      1   373  NA days
4 17706799      1    33  NA days
5 17039253      1   531  NA days
6 23223163      1   230  NA days
7 15848065      1     1  NA days

and I need to create a co-variate time-dependent version of event. How can I do it?

I tried to follow the example 3.2 from this vignette using survival::tmerge, but I didn't succeed.

Dataset:

nd <- structure(list(id = c("22016890", "22042190", "18108887", "17706799", 
"17039253", "23223163", "15848065"), status = c(1, 1, 1, 1, 1, 
1, 1), time = c(459, 83, 373, 33, 531, 230, 1), event = structure(c(425, 
NA, NA, NA, NA, NA, NA), class = "difftime", units = "days")), row.names = c(NA, 
-7L), class = c("tbl_df", "tbl", "data.frame"))

How I need my data:

# A tibble: 8 x 5
  id       start   end status event
  <chr>    <dbl> <dbl>  <dbl> <dbl>
1 22016890     0   425      1     0
2 22016890   425   459      1     1
3 22042190     0    83      1     0
4 18108887     0   373      1     0
5 17706799     0    33      1     0
6 17039253     0   531      1     0
7 23223163     0   230      1     0
8 15848065     0     1      1     0

Solution

  • I managed to do it using this:

    library(survival)
    simpledata <- tmerge(data1 = nd[, c(1:3)], data2 = nd, id = id, tstop = time)
    simpledata <- tmerge(simpledata, nd, id=id, infect = tdc(event))
    simpledata
            id status time tstart tstop infect
    1 22016890      1  459      0   425      0
    2 22016890      1  459    425   459      1
    3 22042190      1   83      0    83      0
    4 18108887      1  373      0   373      0
    5 17706799      1   33      0    33      0
    6 17039253      1  531      0   531      0
    7 23223163      1  230      0   230      0
    8 15848065      1    1      0     1      0