When implementing a model of stochastic disease transmission, one has to deal with a situation in which multiple events are possible. For example, susceptible people may become infected, remain susceptible, or die from other causes. In R, one could use rmultinorm as long as one can assign a probability for each event. Here, however, we implement a function from scratch. One way is to follow the approach of Aaron King, author of the pomp package. His method is implemented in C and I adapted it to R and C++ while removing many of its auxiliary functions (e.g., checking the validity of the inputs).
Code
reulermultinom2 <-function (m=2, size, rate, dt) { trans <-matrix(NA, nrow=m, ncol=length(rate)) p <-0.0# total event rateif ((size <0.0) | (dt <0.0) | (floor(size+0.5) != size)) {for (k inseq_along(rate)) { trans[k] =NaN }return(trans) }if (sum(rate <0.0) >0){stop("Negative rates are not allowed") }else { p <-sum(rate) }if (p >0.0) {for (i in1:m) { tmpsize <-rbinom(1, size = size, prob = (1-exp(-p*dt))) # total number of events tmpp <- pfor (k in1:(length(rate)-1)) { trans[i, k] =rbinom(1, tmpsize, rate[k]/tmpp) tmpsize = tmpsize - trans[i, k]; tmpp = tmpp - rate[k]; } trans[i, length(rate)] = tmpsize; } } return(trans)}
Let’s compare it with the original function provided in the pomp package