如何改变风险数字的列(生存)

How to mutate a column for the number at risk (survival)

作为个人练习,我想知道如何为处于风险中的数字生成一列,或者在时间 t 尚未经历事件的观察的数量。

下面是一些示例数据:

df <- tibble(
  event = c(1,1,1,0,0),
  time = c(10, 20, 30, 40, 50)
)
df

所需的输出应如下所示:

# A tibble: 5 x 3
  event  time nrisk
  <dbl> <dbl> <dbl>
1     1    10     4
2     1    20     3
3     1    30     2
4     0    40     2
5     0    50     2

如果每一行都是一个个体,您可以减去数据框中的行数,累积总和为 event

df$n_risk <- nrow(df) - cumsum(df$event)
df

#  event  time n_risk
#  <dbl> <dbl>  <dbl>
#1     1    10      4
#2     1    20      3
#3     1    30      2
#4     0    40      2
#5     0    50      2

我们可以使用tidyverse

library(dplyr)
df %>% 
    mutate(n_risk = n() - cumsum(event))
# A tibble: 5 x 3
#  event  time n_risk
#  <dbl> <dbl>  <dbl>
#1     1    10      4
#2     1    20      3
#3     1    30      2
#4     0    40      2
#5     0    50      2