Dear all: I've been trying to create a time-to-event variable. Indeed, some time ago, i asked here for help. However, I've detected that it does not fully fulfill my purpose.
Below is my data and the variable I want to create "Time-to-event".
df2 = structure(list(Country = c("USA", "USA", "USA", "USA", "USA",
"USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA"), year = 2000:2012,
Event = c(0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L,
0L), `**Time-to-event**` = c(0L, 1L, 2L, 0L, 1L, 2L, 3L,
0L, 1L, 0L, 1L, 2L, 3L)), .Names = c("Country", "year", "Event",
"**Time-to-event**"), row.names = c(NA, -13L), class = "data.frame")
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
I was suggested to use the following code in order to create the time-to-event varaible
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)
It worked well but the problem with this code is that it counts cases where the Event=1 many years in a row. See below for an example:
Country year Event **Time-to-event**
USA 2000 0 0
USA 2001 0 1
USA 2002 1 2
USA 2003 0 0
USA 2004 1 **1**
USA 2005 1 **2**
USA 2006 1 **3**
USA 2007 0 0
USA 2008 1 1
Instead, I would like it to give a value of zero (0) for cases where the Event variable is 1 in the following years, rather than counting 1's To be clear, this is how I want to see the "time-to-event" variable.
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 1 2
USA 2006 1 0
USA 2007 1 0
USA 2008 1 0
USA 2009 0 0
USA 2010 0 1