How to create Time-to-Event variable?

2019-08-11 09:59发布

问题:

Dear all: I'm thinking of creating a "time to event" variable in R and need your expertice to get it done. Below you can see a small sample of my data. The time variable is in years and it starts at 0 and resets itself when Event = 1.

In the real data the observation period starts in 1989 but there are some countries (that had not ratified certain conventions before 1989) that come in later on, like the US in the example below. Whenever it starts, the first value for the "time to event" variable should be zero.

Thanks for all suggestions!

Country  year              Event      **Time-to-event**
USA      2000               0            0
USA      2001               0            1
USA      2002               1            2
USA      2003               0            0
USA      2004               0            1
USA      2005               0            2
USA      2006               1            3
USA      2007               0            0
USA      2008               1            1
USA      2009               0            0
USA      2010               0            1
USA      2011               0            2
USA      2012               0            3

回答1:

We can use ave

i1 <- with(df2, ave(Event, Country, FUN= 
         function(x) cumsum(c(TRUE, diff(x)<0))))
df2$Time_to_event <- with(df2, ave(i1, i1, Country, FUN= seq_along)-1)

df2$Time_to_event
#[1] 0 1 2 0 1 2 3 0 1 0 1 2 3