October 1, 2018

Basic Concepts

What is Shiny?

Why Shiny?

  • Present results (plots, tables, texts, or even value boxes) interactively without leaving analysis pipelines in R
  • Easy to share after being deployed (just an URL will do)
  • Supported by many other packages, e.g. leaflet and plotly

Built-in demo

library(shiny)

ui <- fluidPage(
   # Application title
   titlePanel("Old Faithful Geyser Data"),
   # Sidebar with a slider input for number of bins 
   sidebarLayout(
      sidebarPanel(
         sliderInput("bins", "Number of bins:",
                     min = 1, max = 50, value = 30)
      ),
      # Show a plot of the generated distribution
      mainPanel(
         plotOutput("distPlot")
      )
   )
)

Built-in demo (cont.)

server <- function(input, output) {
  # generate bins based on input$bins from ui.R
  # draw the histogram with the specified number of bins
   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')
   })
}

# Run the application 
shinyApp(ui = ui, server = server)

More Configurations

More inputs and outputs

  • Shiny cheatsheet
  • Provided by other packages, such as plotly::renderPlotly and plotly::plotlyOutput

HTML tags in Shiny

  • h1 through h6
  • em, code, img, br
  • Use tags list to pick required tag
  • Use HTML to write HTML codes directly
  • BTW, helpText to create help texts

Submit button

  • Delayed execution
  • Usually used when the app takes much time or resource for calculation
  • submitButton, or more versatile, actionButton

Reactivity

  • Reactive expressions
  • Subject to changes in UI inputs
  • Wrapped by reactive function

    # It's like creating a function
    cal_diff <- reactive({
      input$total1 - input$total2
    })
    
    cal_diff()

Combining ggplot2 into Shiny

  • Try to create this app
  • airquality_app.R
  • Using characters in ggplot2 functions
    • aes_string in ggplot
    • paste and as.formula in facet_grid

App Deployment

shinyapps.io

  • Pros:
    • Can be totally free
    • Simple
    • Scalable (?)
  • Cons:
    • Less flexible
    • Limited resources for free plan
  • User Guide for deployment

Shiny Server on VM

Cases and Resources

Case sharing

MOOC and other demos