【问题标题】:recursive sampling in rr中的递归采样
【发布时间】:2011-05-24 18:37:41
【问题描述】:

我正在尝试模拟 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)

如何根据cum.prob 中的累积概率以矢量化方式从tab$id 中采样而不进行替换?从第 1 年采样的 id 不一定在第 2 年再次采样。因此lapply(cum.prob,function(x) sample(tab$id,x*1000)) 将不起作用。可以矢量化吗?

//M

【问题讨论】:

    标签: r sampling


    【解决方案1】:

    这里有一种方法:首先将给定个人在给定年份死亡的概率设为probYrDeath,即probYrDeath[i] = Prob( individual dies in year i ),其中i=1,2,...,7

    probYrDeath <- c(diff(c(0,cum.prob)).
    

    现在根据probYrDeath 中的概率,根据probYrDeath 中的概率,加上到第7 年没有死亡的概率,从1:8 的序列中生成1000 个“死亡年”的随机样本:

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

    我们将“'DeathYr = 8'”解释为“7年内不会死亡”,并提取tab的子集,其中DeathYr != 8

    tab_sample <- subset(tab, DeathYr != 8 )
    

    您可以验证每年的累计死亡比例是否接近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 
    

    【讨论】:

    • 干得好。非常直接的方法。回避了我添加的所有并发症。
    • 哦。比我的好多了!我没有意识到您可以将概率传递给样本。而且差异也很时髦!您可以根据长度(cum.prob)+ 1 设置 8。
    • 非常直观。欣赏它。谢谢。 //M
    • 您还可以通过在前面的行中使用probYrDeath &lt;- diff(c(0, cum.prob, 1)) 来避免c(probYrDeath, 1-sum(probYrDeath)) 而不是probYrDeath 的复杂性
    【解决方案2】:

    这对你有用吗:

    prob.death.per.year<-c(1-cum.prob[length(cum.prob)], cum.prob - c(0, cum.prob[-length(cum.prob)]))
    dead.in.years<-as.vector(rmultinom(1, length(tab$id),prob.death.per.year))[-1]
    totsamp<-sum(dead.in.years)
    data.frame(id=sample(tab$id, totsamp), dead.after=rep(seq_along(dead.in.years), dead.in.years))
    

    根据您希望结果的形式,您可以更改最后一步。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      • 2020-03-05
      • 2013-01-31
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多