More ways to view data: plot and download

Case Studies: Building Web Applications with Shiny in R

Dean Attali

Shiny Consultant

Plot data

  • Plots are common first step when exploring new dataset

    • Plots are outputs
    • Plot output placeholder function in UI:
    plotOutput("my_plot")
    
    • Plot render function in the server:
  output$my_plot <- renderPlot({
      # code for a plot
  })
Case Studies: Building Web Applications with Shiny in R

Download data

  • Downloading is supported using download button

    chapter3_2_more_ways_to_view_data_plot_and_download.009.png

    • Can create any type of file to download
    • image files, text files, CSV files
Case Studies: Building Web Applications with Shiny in R

CSV files

  • Comma Separated Values

  • Store small-medium datasets

  • CSV of gapminder:

    country,continent,year,lifeExp,pop,gdpPercap  
    Afghanistan,Asia,1952,28.801,8425333,779.4453145  
    Afghanistan,Asia,1957,30.332,9240934,820.8530296  
    Afghanistan,Asia,1962,31.997,10267083,853.10071  
    Afghanistan,Asia,1967,34.02,11537966,836.1971382
    
  • Create CSV file:

write.csv(gapminder, "myfile.csv")
Case Studies: Building Web Applications with Shiny in R

Download data in Shiny

  • Download button is treated as output

    • Add download button to UI: (similar to output functions)
    downloadButton(outputId = "download_data", 
                   label = "Download data")
    
    • Add download handler in server: (similar to render functions)
    output$download_data <- downloadHandler(
        filename = "data.csv",
        content = function(file) {
            # Code that creates a file in the path <file>
            write.csv(gapminder, file)
        }
    )
    
Case Studies: Building Web Applications with Shiny in R

Download handler

  output$download_data <- downloadHandler(
      filename = "data.csv",
      content = function(file) {
          # code that creates a file in the path <file>
          write.csv(gapminder, file)
      }
  )
  • downloadHandler() has two arguments
    • filename
      • Name of downloaded file
    • content(file)
      • Function with 1 argument
      • Create the file to download, argument is file path
Case Studies: Building Web Applications with Shiny in R

Let's practice!

Case Studies: Building Web Applications with Shiny in R

Preparing Video For Download...