首页 > 解决方案 > For>while>for 循环减慢这个 R 代码?

问题描述

我提前为这个基本问题道歉,但我认为这可能是某个人的快速指示。

我正在查看这个公开可用的代码,并想知道为什么当负二项式生成的 mu 大于 1 时它运行缓慢(或完全停止)。它与嵌套循环有关吗?

谢谢你。

for(i in 1:runs) {
    cases <- seed
    t <- rep(0,seed)
    times <- t
    while(cases > 0) {
        secondary <- rnbinom(cases,size=fit.cases$estimate[1],mu=fit.cases$estimate[2])
        t.new <- numeric()
        for(j in 1:length(secondary)) {
            t.new <- c(t.new,t[j] + rgamma(secondary[j],shape=fit.serial$estimate[1],
                       rate=fit.serial$estimate[2]))
        }
        cases <- length(t.new)
        t <- t.new
        times <- c(times,t.new)
    }
    lines(sort(times),1:length(times),col=cols[i],lwd=1)
    points(max(times),length(times),col=cols[i],pch=16)
}   

https://github.com/calthaus/Ebola/blob/master/Superspreading%20(Lancet%20Inf%20Dis%202015)/Ebola_superspreading_analysis.R

标签: rfor-loopwhile-loop

解决方案


推荐阅读