参考以下R中的时间依赖性生存手册:
https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf
从渐晕的例子来看:
subject time1 time2 death creatinine
5 0 90 0 0.9
5 90 120 0 1.5
5 120 185 1 1.2
我的数据格式如下:
dd-mm-yyyy格式
subject date death creatinine
5 01-01-2022 0 0.9
5 01-04-2022 0 1.5
5 01-05-2022 0 1.2
5 05-07-2022 1 1.2
我需要格式化下面的数据以匹配上面的数据。
如果没有更多信息,就无法在最后一行填写time2
。在单个事件数据中,如果个人有该事件(如您的示例(,则最后一行中的time2
值通常是该事件(在最后一行(的时间。对于那些没有事件的人来说,time2
可能是该个体观察结束的时间。
因此,排除每个subject
的最终time2
值,您可以执行类似的操作
library(dplyr)
df %>%
# change date to Date using as.Date()
mutate(date=as.Date(date,"%d-%m-%y")) %>%
# arrange the rows by date
arrange(date) %>%
# group by subject
group_by(subject) %>%
# for each subject, create time2 and time1
mutate(
time2 = as.numeric(lead(date)-min(date)-1),
time1 = lag(time2),
time1 = if_else(row_number()==1, 0, time1)
) %>%
ungroup() %>%
# move time1 next to time2
relocate(time1,.before = time2)
输出:
subject date death creatinine time1 time2
<int> <date> <int> <dbl> <dbl> <dbl>
1 5 2020-01-01 0 0.9 0 90
2 5 2020-04-01 0 1.5 90 120
3 5 2020-05-01 1 1.2 120 NA