首页 > 解决方案 > R中基于不规则间隔的生存数据表示

问题描述

我有以下数据集:

df =
id Time A
1  3    0
1  5    1
1  6    1
2  8    0
2  9    0
2  12   1

我想做两件事:i)所有id的开始时间为-1,ii)将时间分成两列;开始和结束,同时保留个人获得观察 A 的时间(将结束设置为参考点)。最终结果应如下所示:

df = 
id start end A
1  -1     0  0  
1  0      2  1
1  2      3  1
2  -1     0  0
2  0      1  0
2  1      4  1

标签: rdataframesurvival

解决方案


这可以解决这个问题。我对描述中的问题不是 100% 确定的,所以试图摆脱我在这里看到的内容。为了将来参考,请尝试粘贴dput(df)作为输入数据:)

df <- data.frame(id=c(rep(1,3),rep(2,3)),
                 Time=c(3,5,6,8,9,12),
                 A=c(0,1,1,0,0,1))

library(data.table)
dt <- as.data.table(df)
# diff(Time) finds the interval between points
# cumsum then adds this diff together to take in to account the previous time
# gaps
dt[, end := cumsum(c(0, diff(Time))), by=id]

# start is then just a shifted version of end, with the initial start filled as -1
dt[, start := shift(end, n=1, fill=-1), by=id]

out <- as.data.frame(dt)
out

推荐阅读