r-代码成功运行,但没有图形作为输出



我正试图在巴基斯坦的案例中复制Fabian Dablander的《非线性感染》的工作。但当我运行下面的代码时,它不会将任何图形作为输出">

plot_SIR <- function(res, main = '') {
cols <- brewer.pal(3, 'Set1')
matplot(
res, type = 'l', col = cols, axes = FALSE, lty = 1, lwd = 2,
ylab = 'Subpopulations(t)', xlab = 'Time t', xlim = c(0, 4000),
ylim = c(0, 1), main = main, cex.main = 1.75, cex.lab = 1.5,
font.main = 1, xaxs = 'i', yaxs = 'i'
)
axis(1, cex.axis = 1.25)
axis(2, las = 2, cex.axis = 1.25)
legend(
3000, 0.65, col = cols, legend = c('S', 'I', 'R'),
lty = 1, lwd = 2, bty = 'n', cex = 1.5
)
}

快速查看一下,您需要运行另一个函数来获得param:res,然后将其粘贴在原始函数中,就像您在文章中描述的那样:

solve_SIR <- function(S0, I0, beta = 1, gamma = 1, delta_t = 0.01, times = 8000) {
res <- matrix(
NA, nrow = times, ncol = 4, dimnames = list(NULL, c('S', 'I', 'R', 'Time'))
)
res[1, ] <- c(S0, I0, 1 - S0 - I0, delta_t)
dS <- function(S, I) -beta * I * S
dI <- function(S, I)  beta * I * S - gamma * I
for (i in seq(2, times)) {
S <- res[i-1, 1]
I <- res[i-1, 2]
res[i, 1] <- res[i-1, 1] + delta_t * dS(S, I)
res[i, 2] <- res[i-1, 2] + delta_t * dI(S, I)
res[i, 4] <- delta_t * i
}
res[, 3] <- 1 - res[, 1] - res[, 2]
res
}

使用函数生成参数输入,并为S0和I0选择随机值,这将输出您想要的图形。

plot_SIR(solve_SIR(0.95, 0.05))

最新更新