Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cloud/models/r/r_shiny/app.R
6405 views
1
# Find out more about building applications with Shiny here:
2
#
3
# http://shiny.rstudio.com/
4
#
5
library(shiny)
6
library(deSolve)
7
8
# SIR mathematical model
9
sir <- function(time, state, parameters) {
10
with(as.list(c(state, parameters)), {
11
dS <- -beta * S * I
12
dI <- beta * S * I - gamma * I
13
dR <- gamma * I
14
15
return(list(c(dS, dI, dR)))
16
})
17
}
18
19
# Define UI for app that draws SIR equations ----
20
ui <- fluidPage(
21
22
# App title ----
23
titlePanel("SIR MODEL EXAMPLE"),
24
25
# Sidebar layout with input and output definitions ----
26
sidebarLayout(
27
28
# Sidebar panel for inputs ----
29
sidebarPanel(
30
31
# Input: Slider for time range ----
32
sliderInput(inputId = "time_range",
33
label = "Time range:",
34
min = 10,
35
max = 1000,
36
value = 30),
37
# Input: Slider for the value of 'beta' - infection ratio ----
38
sliderInput(inputId = "infection_ratio",
39
label = "Infection ratio:",
40
min = 0.01,
41
max = 10.0,
42
value = 1.2),
43
# Input: Slider for the value of 'gamma' - recover ratio ----
44
sliderInput(inputId = "recover_ratio",
45
label = "Recover ratio:",
46
min = 0.01,
47
max = 1,
48
value = 0.1),
49
# Input: Slider for the value of 'S' - Susceptible individuals percentage ----
50
sliderInput(inputId = "susceptible_percentage",
51
label = "Susceptible percentage:",
52
min = 0.00001,
53
max = 0.99999,
54
value = 0.99999)
55
),
56
57
# Main panel for displaying outputs ----
58
mainPanel(
59
60
# Output: SIR equations ----
61
plotOutput(outputId = "sirPlot")
62
)
63
)
64
)
65
66
# Define server logic required to draw SIR equations ----
67
server <- function(input, output) {
68
69
# 1. It is "reactive" and therefore should be automatically
70
# re-executed when inputs change
71
# 2. Its output type is a plot
72
output$sirPlot <- renderPlot({
73
74
infected_number = 1 - input$susceptible_percentage
75
76
init <- c(S = input$susceptible_percentage, I = infected_number, R = 0)
77
parameters <- c(beta = input$infection_ratio, gamma = input$recover_ratio)
78
times <- seq(0, input$time_range, by = 1)
79
80
out <- as.data.frame(ode(y = init, times = times, func = sir, parms = parameters))
81
out$time <- NULL
82
83
matplot(times, out, type = "l", xlab = "Time", ylab = "Susceptibles, Infected and Recovered", main = "SIR Model", lwd = 1, lty = 1, bty = "l", col = 2:4)
84
legend(40, 0.7, c("Susceptibles", "Infected", "Recovered"), pch = 1, col = 2:4)
85
})
86
87
}
88
89
# Create Shiny app ----
90
shinyApp(ui = ui, server = server)
91