Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

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

As a personal exercise, I was wondering how to generate a column for the number at risk, or the number of observations that have not yet experienced the event at time t.

Here's some sample data:

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

The desired output should look like:

# 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
question from:https://stackoverflow.com/questions/65865871/how-to-mutate-a-column-for-the-number-at-risk-survival

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...