2

试图将我的思想围绕矢量化,试图使一些模拟更快,我发现了这个非常基本的流行病模拟。代码来自本书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循环。我的问题是,由于代码从and值生成S[i+1]and值,是否可以使用 apply 函数对其进行矢量化?R[i+1]S[i]R[i]

非常感谢

4

1 回答 1

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)
}
于 2012-05-26T23:55:22.530 回答