开始使用免费开始使用

下载筛选后的数据

下载文件可以通过成对使用 downloadButton()downloadHandler() 来实现。它们的配合方式与输出函数和渲染函数类似:downloadButton() 决定它在 UI 中出现的位置,而 downloadHandler() 需要保存到 output 列表中,并包含实际用于创建下载文件的 R 代码。

本练习是课程的一部分

案例研究:使用 R 的 Shiny 构建 Web 应用

查看课程

练习说明

为当前表格中显示的数据添加下载为 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)
编辑并运行代码