矢量化模拟

时间:2012-05-26 21:59:01

标签: r vectorization

试图将我的思维包裹在矢量化中,尝试更快地进行模拟,我发现了这种非常基本的流行病模拟。代码来自书籍http://www.amazon.com/Introduction-Scientific-Programming-Simulation-Using/dp/1420068725/ref=sr_1_1?ie=UTF8&qid=1338069156&sr=8-1

#program spuRs/resources/scripts/SIRsim.r

SIRsim <- function(a, b, N, T) {
  # Simulate an SIR epidemic
  # a is infection rate, b is removal rate
  # N initial susceptibles, 1 initial infected, simulation length T
  # returns a matrix size (T+1)*3 with columns S, I, R respectively
  S <- rep(0, T+1)
  I <- rep(0, T+1)
  R <- rep(0, T+1)
  S[1] <- N
  I[1] <- 1
  R[1] <- 0
  for (i in 1:T) {
    S[i+1] <- rbinom(1, S[i], (1 - a)^I[i])
    R[i+1] <- R[i] + rbinom(1, I[i], b)
    I[i+1] <- N + 1 - R[i+1] - S[i+1]
  }
  return(matrix(c(S, I, R), ncol = 3))
}

模拟的核心是for循环。我的问题是,由于代码从S[i+1]R[i+1]值生成S[i]R[i]值,是否可以使用apply函数对其进行矢量化?

非常感谢

1 个答案:

答案 0 :(得分:5)

很难“迭代”迭代计算,但这是一个模拟和模拟很可能会运行多次。因此,通过添加参数M(要执行的模拟次数),分配M x(T + 1)矩阵,然后填充连续列(次数)来写这个以同时进行所有模拟每个模拟。这些变化似乎非常直接(所以我可能犯了一个错误;我特别关注在rbinom的第二和第三个参数中使用向量,尽管这与文档一致)

SIRsim <- function(a, b, N, T, M) {
    ## Simulate an SIR epidemic
    ## a is infection rate, b is removal rate
    ## N initial susceptibles, 1 initial infected, simulation length T
    ## M is the number of simulations to run
    ## returns a list of S, I, R matricies, each M simulation
    ## across T + 1 time points
    S <- I <- R <- matrix(0, M, T + 1)
    S[,1] <- N
    I[,1] <- 1
    for (i in seq_along(T)) {
        S[,i+1] <- rbinom(M, S[,i], (1 - a)^I[,i])
        R[,i+1] <- R[,i] + rbinom(M, I[,i], b)
        I[,i+1] <- N + 1 - R[,i+1] - S[,i+1]
    }
    list(S=S, I=I, R=R)
}