If every row is an individual you could subtract number of rows in the dataframe with cumulative sum of 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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…