R中基于不规则间隔的生存数据表示
Irregular Interval based representation of survival data in 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
这组就可以了。我对描述中的问题不是 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
我有以下数据集:
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
这组就可以了。我对描述中的问题不是 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