開始使用免費開始

下載篩選後的資料

下載檔案是透過 downloadButton()downloadHandler() 這一組函式完成的。這兩個函式的搭配方式類似於 output 與 render 函式:downloadButton() 負責決定它會出現在 UI 的哪裡,而 downloadHandler() 需要儲存在 output 清單中,並包含實際用來建立下載檔案的 R 程式碼。

本練習屬於課程

案例研究:使用 R 的 Shiny 建置網頁應用程式

檢視課程

練習說明

為目前在表格中檢視的資料新增下載成 CSV 檔的功能。具體請執行:

  • 在 UI 中新增一個 ID 為「download_data」、標籤為「Download」的下載按鈕。
  • 在伺服端新增一個下載處理器(第 31 行)。
  • 將下載檔案的名稱設為「gapminder_data.csv」(第 33 行)。
  • 將篩選後的資料寫入 CSV 檔(第 50 行)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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)
編輯並執行程式碼