You can also define your gradient function (and other non-changing elements) outside the loop:
SIR <- function(time,state,parameters) {
with(as.list(c(state,parameters)),{
dS <- -beta*S*I
dI <- beta*S*I-gamma*I
dR <- gamma*I
return(list(c(dS,dI,dR)))
})
}
init <- c(S=1-1e-6, I=1e-6, R=0)
time <- seq(0,80,by=1)
Now define the vector of values to try (not necessary, but convenient):
betavec <- seq(1,2,by=0.1)
and define a list to store the results:
res <- vector(length(betavec),mode="list")
library(deSolve)
for (k in seq_along(betavec)){
res[[k]] <- ode(y=init,times=time,func=SIR,
parms=c(beta=betavec[k], gamma=0.15))
}
, . sapply lapply , . :
t(sapply(res,tail,1))
, ...
names(res) <- betavec
dd <- dplyr::bind_rows(lapply(res,as.data.frame),.id="beta")
dd$beta <- as.numeric(dd$beta)
do.call(rbind,...) , bind_rows(), bind_rows. id beta . lines() (,) matplot(), . .
library(ggplot2); theme_set(theme_bw())
library(viridis)
ggplot(dd,aes(x=time,y=I,colour=beta))+
geom_line(aes(group=beta))+
scale_color_viridis()+
scale_y_log10()
