-
Notifications
You must be signed in to change notification settings - Fork 71
/
sir-example.Rmd
68 lines (50 loc) · 1.61 KB
/
sir-example.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
---
title: "SIR Model Example"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(deSolve)
```
**Credit:** This example is built on (and closely follows) the example presented [here](http://rstudio-pubs-static.s3.amazonaws.com/6852_c59c5a2e8ea3456abbeb017185de603e.html) by Dr. Aidan Findlater
## Set up: define parameters
```{r}
### Specify parameters
## Proportion in each compartment: Susceptible 0.999999, Infected 0.000001, Recovered 0 (these are directly from the example linked above)
init <- c(S = 1-1e-6, I = 1e-6, R = 0.0)
## beta: infection parameter; gamma: recovery parameter
parameters <- c(beta = 2.316, gamma = 0.261)
## Time frame
times <- seq(0, 100, by = 0.5)
```
## Create the function with the differential equations:
```{r}
## Build the function with all
sir <- function(time, init, parameters) {
with(as.list(c(init, parameters)), {
dS <- -beta * S * I
dI <- beta * S * I - gamma * I
dR <- gamma * I
return(list(c(dS, dI, dR)))
})
}
```
## Approximate the solution using `deSolve::ode()`:
```{r}
## Solve using `deSolve::ode()`
approximation <- ode(y = init, times = times, func = sir, parms = parameters)
```
## Make it something we can plot:
```{r}
## Get output into a data frame
approx_df <- as.data.frame(approximation)
## Pivot longer so R will do the work for us:
approx_long <- approx_df %>%
pivot_longer(cols = S:R, names_to = "population", values_to = "proportion")
```
## Plot the output with ggplot:
```{r}
ggplot(data = approx_long, aes(x = time, y = proportion)) +
geom_line(aes(color = population))
```
## End