April, 15, 2020

Shiny

Shiny is an R package that makes it easy to build interactive web apps straight from R. You can host standalone apps on a webpage or embed them in R Markdown documents or build dashboards. You can also extend your Shiny apps with CSS themes, htmlwidgets, and JavaScript actions. (shiny.rstudio.com)

What’s in a Shiny app?

library(shiny)

ui <- fluidPage()

server <- function(input, output, session) { }

shinyApp(ui = ui, server = server)

Or as three files…

  • global.R - R code that is executed when the app starts.
  • ui.R - Defines the user interface.
  • server.R - Defines the “business” logic (i.e. generate plots, tables, etc.)

global.R

library(shiny)
library(tidverse)

# Load data
data('faithful')

ui.R

shinyUI(fluidPage(
    titlePanel("Old Faithful Geyser Data"),
    sidebarLayout(
        sidebarPanel(
            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30)
        ),
        mainPanel(
            plotOutput("distPlot")
        )
    )
))

server.R

shinyServer(function(input, output) {
    output$distPlot <- renderPlot({
        x    <- faithful[, 2]
        bins <- seq(min(x), max(x), length.out = input$bins + 1)
        hist(x, breaks = bins, col = 'darkgray', border = 'white')

    })
})