r - 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
推荐阅读
- python - 无论如何要以确定的尺寸拍摄脸部照片吗?
- python - 如何在python中迭代条件检查?
- r - R在值的出现达到限制后从数据框中删除行
- c++ - Xcode - 移动 src 文件后丢失 .h 和 .cpp 文件数据
- javascript - 未正确填写特定框时如何更改其颜色
- css - 悬停样式 '&:hover:{ }' 不适用于反应组件中的按钮
- android - Android RSA 加密抛出 InvalidKeySpecException
- python - 返回列表中的最低点
- rubygems - 带有 netlify 的 Asciidoc hugo 站点
- javascript - 如何将本地 csv 文件加载到 JavaScript 数组中