Path: blob/master/cloud/models/r/r_shiny/app.R
6405 views
# Find out more about building applications with Shiny here:1#2# http://shiny.rstudio.com/3#4library(shiny)5library(deSolve)67# SIR mathematical model8sir <- function(time, state, parameters) {9with(as.list(c(state, parameters)), {10dS <- -beta * S * I11dI <- beta * S * I - gamma * I12dR <- gamma * I1314return(list(c(dS, dI, dR)))15})16}1718# Define UI for app that draws SIR equations ----19ui <- fluidPage(2021# App title ----22titlePanel("SIR MODEL EXAMPLE"),2324# Sidebar layout with input and output definitions ----25sidebarLayout(2627# Sidebar panel for inputs ----28sidebarPanel(2930# Input: Slider for time range ----31sliderInput(inputId = "time_range",32label = "Time range:",33min = 10,34max = 1000,35value = 30),36# Input: Slider for the value of 'beta' - infection ratio ----37sliderInput(inputId = "infection_ratio",38label = "Infection ratio:",39min = 0.01,40max = 10.0,41value = 1.2),42# Input: Slider for the value of 'gamma' - recover ratio ----43sliderInput(inputId = "recover_ratio",44label = "Recover ratio:",45min = 0.01,46max = 1,47value = 0.1),48# Input: Slider for the value of 'S' - Susceptible individuals percentage ----49sliderInput(inputId = "susceptible_percentage",50label = "Susceptible percentage:",51min = 0.00001,52max = 0.99999,53value = 0.99999)54),5556# Main panel for displaying outputs ----57mainPanel(5859# Output: SIR equations ----60plotOutput(outputId = "sirPlot")61)62)63)6465# Define server logic required to draw SIR equations ----66server <- function(input, output) {6768# 1. It is "reactive" and therefore should be automatically69# re-executed when inputs change70# 2. Its output type is a plot71output$sirPlot <- renderPlot({7273infected_number = 1 - input$susceptible_percentage7475init <- c(S = input$susceptible_percentage, I = infected_number, R = 0)76parameters <- c(beta = input$infection_ratio, gamma = input$recover_ratio)77times <- seq(0, input$time_range, by = 1)7879out <- as.data.frame(ode(y = init, times = times, func = sir, parms = parameters))80out$time <- NULL8182matplot(times, out, type = "l", xlab = "Time", ylab = "Susceptibles, Infected and Recovered", main = "SIR Model", lwd = 1, lty = 1, bty = "l", col = 2:4)83legend(40, 0.7, c("Susceptibles", "Infected", "Recovered"), pch = 1, col = 2:4)84})8586}8788# Create Shiny app ----89shinyApp(ui = ui, server = server)9091