Chapter 4 Shiny web applications

This part comes from the tutorial of Benoît Thieurmel. It is available here https://github.com/datastorm-open/tuto_shiny_rennes.

4.1 First app

Create a new repository for the application (in RStudio):

File -> New Project -> New Directory -> Shiny Web Application

Choose an application Multiple File.

If the option Multiple File (it depends on the version of Rstudio) is not possible, you can use

File -> New File -> Shiny Web App -> Multiple File

Two files are automatically created: ui.R and server.R. Run the application with the button Run App.

  • Change the title of the application. You can call it My first application.
  • Update the application and check that the new title appears.

4.2 Input - output

We keep the same application, we don’t care about the structure (rows, columns, tabs…) for the moment. We just want to add:

  • new inputs in sidebarPanel, after the sliderInput. Don’t forget to add commas to separate the inputs;
  • new outputs in mainPanel, after the plotOutput. Don’t forget to add commas to separate the outputs.

To summarize, we want one column for all the inputs and another one for all the outputs.

  1. Add in ui.R an input which allows to change the color of the histogram. You can use this command:

    selectInput(inputId = "color", label = "Couleur :",
                choices = c("Rouge" = "red", "Vert" = "green", "Bleu" = "blue"))
  2. Add a new output to visualize the summary of the dataset faithful. You can use:

    # ui.R
    verbatimTextOutput("...")
    
    # server.R
    output$... <- renderPrint({
      summary(...)
    })

Exercise 4.1 (Adding some inputs/outputs) Add some inputs and outputs on the previous application to

  1. propose to the user to change the title of the histogram (use a textInput in the ui and the option main in the hist function);

  2. select the variable of faithful for the histogram (use a radioButtons with choices colnames(faithful));

  3. visualize the whole dataset faithful (renderDataTable & dataTableOutput);

  4. add a text under the histogram which indicates the number of class (use renderText and paste functions in server, textOutput in ui).

  5. replace the selectInput of the color choice by a colourInput (use colourpicker package);

  6. export the graph (downloadButton & jpeg).

The final application may look like https://input-output-rouviere-shiny.apps.math.cnrs.fr.

4.3 Organizing the application

Exercise 4.2 (Structure of an application) Consider the application app_structure available here. It is quite the same as the previous one with a navbarPage which defines

  • a tab Data to visualize the data (table + summary)
  • a tab Visualisation : inputs + histogram.
  1. Tab Data: use navlistPanel to separate the summary and the table into two tabs:

    # rappel de la structure (ui.R)
    navlistPanel(
    "Title of the structure",
    tabPanel("Title of the tab", ... "(content of the tab)"),
    tabPanel("Title of the tab", ... "(content of the tab)")
    )
  2. Tab Visualization: change sidebarLayout - sidebarPanel - mainPanel by a fluidRow with 2 columns:

    • 1/4: for the sidebarPanel
    • 3/4: for the mainPanel.
    fluidRow(
      column(width = 3, ...), # column 1/4 (3/12)
      column(width = 9, ...)  # column 3/4 (9/12)
    )

    Hint: use wellPanel for the left column.

  3. Add a boxplot in the visualisation tab (same variable and same color). You can also use tabsetPanel to obtain two different tabs for the histogram and the boxplot.

    # rappel de la structure (ui.R)
    tabsetPanel(
    tabPanel("Title of the tab", ... "(content of the tab)"),
    tabPanel("Title of the tab", ... "(content of the tab)")
    )

The final application may look libe https://structure-rouviere-shiny.apps.math.cnrs.fr.

Taking things further: use shinydashboard (https://rstudio.github.io/shinydashboard/) for building the same application.

4.4 Adding interactive charts

In the previous application, replace histogram and boxplots by javascript charts obtained with rAmCharts. You can use (see https://interactifs-rouviere-shiny-2.apps.math.cnrs.fr)

# server.R
output$distPlot <- renderAmCharts({...})

# ui.R
amChartsOutput("...")

4.5 Reactive, isolation, observe, html, …

Keep the previous application and

  • add actionButton combined with isolate to update the application only when we click on a button.

  • Use observeEvent to force the visualization of the histogram when we update the application. You can use

    # think to add  "session" 
    shinyServer(function(input, output, session)
    
    # an id 
    tabsetPanel(id = "viz", 
      tabPanel("Histogram", ...
    
    # and finaly
    observeEvent(input$go, {
    updateTabsetPanel(session, inputId = "viz", selected = "Histogram")
    })  
  • Use reactive function to store the selected variable

    # Example of reactive
    data <- reactive({
      ...
    })
    
    output$plot <- renderPlot({
      x <- data()
      ...
    })
  • Add a title on the dataset with blue color. You can use h1 function:

    h1("Dataset", style = "color : #0099ff;text-align:center")
  • Add a third tab where you present a summary of your school. You can also add an image and a link to a website (see https://plus-loin-rouviere-shiny-2.apps.math.cnrs.fr).

  • Taking things further: change the theme of the application with a .css file. You can use bootswatch for instance http://bootswatch.com/3.

4.6 Some additional exercises

Exercise 4.3 (Descriptive statistics) We consider the dataset SAheart from the bestglm package.

  1. Use rAmCharts to visualize histograms of the numeric variables of the dataset and boxplots in terms of the variable chd.

  2. Create a shiny web application (you can use shinydashboard) which allows to

    • select one variable among the numeric variables of the dataset. You can use radioButtons with
    choices=names(SAheart)[sapply(SAheart,class)=="numeric"]
    • visualize the histogram and the boxplot (in terms of chd) of the selected variable. These graphsshould be done with rAmCharts (use amChartsOutput).

    • The required application may look like

It is also available at https://lrouviere.shinyapps.io/DESC_APP.

Exercise 4.4 (Bike stations in Rennes) Create an application which allows to visualize bike stations in Rennes. It may look like

It is also available at https://lrouviere.shinyapps.io/velib/. You can obtain the data on the Rennes métropole website: https://data.rennesmetropole.fr/explore/dataset/etat-des-stations-le-velo-star-en-temps-reel/export/