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')

    })
})

Reactions

The input$ list stores the current value of each input object under its name.

Shiny Reactions

Formatting Text

Shiny Function HTML Equivalent Creates
p <p> A paragraph of text
h1 <h1> A first level header
h2 <h2> A second level header
h3 <h3> A third level header
h4 <h4> A fourth level header
h5 <h5> A fifth level header
h6 <h6> A sixth level header
a <a> A hyper link (need href parameter)
br <br> A line break
div <div> A division of text with a uniform style
pre <pre> Unformatted text
code <code> A formatted block of code
img <img> An image (need src parameter)
strong <strong> Bold text
em <em> Italicized text
HTML HTML code passed directly to the browser

Including R code in while running the app

runApp(display.mode="showcase")

Additional Resources