r中的递归采样

Mis*_*sha 4 r sampling

我试图模拟死亡超过7年的累积概率如下:

tab <- data.frame(id=1:1000,char=rnorm(1000,7,4))

cum.prob <- c(0.05,0.07,0.08,0.09,0.1,0.11,0.12)
Run Code Online (Sandbox Code Playgroud)

如何tab$id根据累积概率以矢量化方式从无需替换的样本中进行采样cum.prob?从年1开始采样的ids不一定能在2年内再次采样.因此,lapply(cum.prob,function(x) sample(tab$id,x*1000))它不起作用.有可能对此进行矢量化吗?

//中号

Pra*_*ani 7

这是一种方式:首先得到给定个体在给定年份死亡的概率probYrDeath,即probYrDeath[i] = Prob( individual dies in year i )在哪里i=1,2,...,7.

probYrDeath <- c(diff(c(0,cum.prob)).
Run Code Online (Sandbox Code Playgroud)

现在生成1000个"死亡年"的随机样本,替换,从序列1:8,根据概率probYrDeath,增加了不到第7年死亡的概率:

set.seed(1) ## for reproducibility
tab$DeathYr <- sample( 8, 1000, replace = TRUE, 
                       prob = c(probYrDeath, 1-sum(probYrDeath)))
Run Code Online (Sandbox Code Playgroud)

我们的解释是"'DeathYr = 8’"为"不7年内死亡",并提取的子集tab,其中DeathYr != 8:

tab_sample <- subset(tab, DeathYr != 8 )
Run Code Online (Sandbox Code Playgroud)

您可以验证每年的累计死亡比例是否接近以下值cum.prob:

> cumsum(table(tab_sample$DeathYr)/1000)
    1     2     3     4     5     6     7 
0.045 0.071 0.080 0.094 0.105 0.115 0.124 
Run Code Online (Sandbox Code Playgroud)