如何创建事件时间变量? [英] How to create Time-to-Event variable?
问题描述
亲爱的所有人:我正在考虑在R中创建一个事件发生时间"变量,需要您的专业知识才能完成.您可以在下面看到我的数据的一小部分样本.时间变量以年为单位,从0开始,并在Event = 1时重置.
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.
在真实数据中,观察期始于1989年,但随后出现了一些国家(1989年之前尚未批准某些公约),例如以下示例中的美国.每当启动时,事件发生时间"变量的第一个值应为零.
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.
感谢所有建议!
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
推荐答案
我们可以使用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
这篇关于如何创建事件时间变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!