R
shiny
Mar 24, 2017     2 minutes read

1. What is shiny and why would you use it?

Sounds like a dream?

Concluding, I’ve got mixed feelings about shiny. As a data scientist, maybe you should concentrate on fitting models and wrangling data instead of preparing a bright and shiny front-end.

2. A “Hello World” example:

You can store your application in one file (e.g. “app.R”), like this:

library(shiny)

inputBins <- 10

ui <- shinyUI(fluidPage(

  titlePanel("Hello Shiny!"),

  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
        "Choose your favourite number:",
        min = 1,
        max = 50,
        value = 30)
    ),

    mainPanel(
      plotOutput("distPlot")
    )
  )
))

server <- shinyServer(function(input, output) {

    r <- reactiveValues()

    observeEvent(input$bins, {
        r$bins <- input$bins
        output$distPlot <- renderPlot(f())
    })

    f <- function() {
        x <- faithful[, 2]
        inputBins <- r$bins
        bins <- seq(min(x), max(x), length.out = inputBins  + 1)
        hist(x, breaks = bins, col = 'darkgray', border = 'white')
    }

})

shinyApp(ui, server)

and run it with

Rscript app.R

or divide it into two separate files:

ui.R

library(shiny)

ui <- shinyUI(fluidPage(

  titlePanel("Hello Shiny!"),

  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
        "Choose your favourite number:",
        min = 1,
        max = 50,
        value = 30)
    ),

    mainPanel(
      plotOutput("distPlot")
    )
  )
))

server.R

library(shiny)

inputBins <- 10

server <- shinyServer(function(input, output) {

    r <- reactiveValues()

    observeEvent(input$bins, {
        r$bins <- input$bins
        output$distPlot <- renderPlot(f())
    })

    f <- function() {
        x <- faithful[, 2]
        inputBins <- r$bins
        bins <- seq(min(x), max(x), length.out = inputBins  + 1)
        hist(x, breaks = bins, col = 'darkgray', border = 'white')
    }

})

and run it with

Rscript -e "shiny::runApp()"

or from within the R console

shiny::runApp()