CommencerCommencer gratuitement

Download the filtered data

Downloading files is achieved using the pair of functions downloadButton() and downloadHandler(). These two functions pair together similarly to how output and render functions are paired: downloadButton() determines where in the UI it will show up, while downloadHandler() needs to be saved into the output list and has the actual R code to create the downloaded file.

Cet exercice fait partie du cours

Case Studies: Building Web Applications with Shiny in R

Afficher le cours

Instructions

Add the ability to download the data that is currently viewed in the table as a CSV file. Specifically:

  • Add a download button to the UI with ID "download_data" and a label of "Download".
  • Add a download handler to the server (line 31).
  • Give the downloaded file a name of "gapminder_data.csv" (line 33).
  • Write the filtered data into a CSV file (line 50).

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

ui <- fluidPage(
  h1("Gapminder"),
  sliderInput(inputId = "life", label = "Life expectancy",
              min = 0, max = 120,
              value = c(30, 50)),
  selectInput("continent", "Continent",
              choices = c("All", levels(gapminder$continent))),
  # Add a download button
  ___(outputId = ___, label = ___),
  plotOutput("plot"),
  tableOutput("table")
)

server <- function(input, output) {
  output$table <- renderTable({
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    if (input$continent != "All") {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    data
  })

  # Create a download handler
  output$download_data <- ___(
    # The downloaded file is named "gapminder_data.csv"
    filename = ___,
    content = function(file) {
      # The code for filtering the data is copied from the
      # renderTable() function
      data <- gapminder
      data <- subset(
        data,
        lifeExp >= input$life[1] & lifeExp <= input$life[2]
      )
      if (input$continent != "All") {
        data <- subset(
          data,
          continent == input$continent
        )
      }
      
      # Write the filtered data into a CSV file
      write.csv(___, file, row.names = FALSE)
    }
  )

  output$plot <- renderPlot({
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    if (input$continent != "All") {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point() +
      scale_x_log10()
  })
}

shinyApp(ui, server)
Modifier et exécuter le code