我正在嘗試使用dplyr管道創建 Kaplan-Meier 生命表。我無法在不使用 for 回圈的情況下計算累積生存概率。這是一些示例資料。
df <- tibble(
months = c(1, 3, 9, 13, 17, 20),
n_at_risk = c(10, 8, 7, 5, 3, 2),
cond_prob_event = c(0.100, 0.125, 0.143, 0.200, 0.333, 0.500),
cond_prob_surv = c(0.900, 0.875, 0.857, 0.800, 0.667, 0.50)
)
df
# A tibble: 6 × 4
months n_at_risk cond_prob_event cond_prob_surv
<dbl> <dbl> <dbl> <dbl>
1 1 10 0.1 0.9
2 3 8 0.125 0.875
3 9 7 0.143 0.857
4 13 5 0.2 0.8
5 17 3 0.333 0.667
6 20 2 0.5 0.5
在這種情況下,累積生存概率計算為先前(滯后)累積生存概率與當前條件生存概率的乘積。我可以使用 for 回圈得到我正在尋找的答案:
out <- vector(mode = "numeric", 6)
for (i in seq_along(df$cond_prob_surv)) {
if (i == 1) {
out[i] <- df$cond_prob_surv[i]
} else {
out[i] <- out[i - 1] * df$cond_prob_surv[i]
}
}
df$cum_prob_survival <- out
df
# A tibble: 6 × 5
months n_at_risk cond_prob_event cond_prob_surv cum_prob_survival
<dbl> <dbl> <dbl> <dbl> <dbl>
1 1 10 0.1 0.9 0.9
2 3 8 0.125 0.875 0.788
3 9 7 0.143 0.857 0.675
4 13 5 0.2 0.8 0.540
5 17 3 0.333 0.667 0.360
6 20 2 0.5 0.5 0.180
但是,出于某些原因,我真的很想找到dplyr唯一的解決方案。任何幫助是極大的贊賞!
uj5u.com熱心網友回復:
我們cumprod這里可能需要
library(dplyr)
df <- df %>%
mutate(cum_prob_survival = cumprod(cond_prob_surv))
-輸出
df
# A tibble: 6 × 5
months n_at_risk cond_prob_event cond_prob_surv cum_prob_survival
<dbl> <dbl> <dbl> <dbl> <dbl>
1 1 10 0.1 0.9 0.9
2 3 8 0.125 0.875 0.788
3 9 7 0.143 0.857 0.675
4 13 5 0.2 0.8 0.540
5 17 3 0.333 0.667 0.360
6 20 2 0.5 0.5 0.180
或者另一種選擇是 accumulate
library(purrr)
df <- df %>%
mutate(cum_prob_survival = accumulate(cond_prob_surv, `*`))
-輸出
df
# A tibble: 6 × 5
months n_at_risk cond_prob_event cond_prob_surv cum_prob_survival
<dbl> <dbl> <dbl> <dbl> <dbl>
1 1 10 0.1 0.9 0.9
2 3 8 0.125 0.875 0.788
3 9 7 0.143 0.857 0.675
4 13 5 0.2 0.8 0.540
5 17 3 0.333 0.667 0.360
6 20 2 0.5 0.5 0.180
uj5u.com熱心網友回復:
使用基本 R 選項 Reduce
transform(
df,
cum_prob_survival = Reduce(`*`, cond_prob_surv, accumulate = TRUE)
)
給
months n_at_risk cond_prob_event cond_prob_surv cum_prob_survival
1 1 10 0.100 0.900 0.9000000
2 3 8 0.125 0.875 0.7875000
3 9 7 0.143 0.857 0.6748875
4 13 5 0.200 0.800 0.5399100
5 17 3 0.333 0.667 0.3601200
6 20 2 0.500 0.500 0.1800600
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/358114.html
