開始使用免費開始

用 reactive 變數減少重複程式碼

在前面的練習中,依據輸入值篩選 gapminder 的程式碼重複了 3 次:各在表格、圖形,以及下載處理器中各一次。

使用 reactive 變數可以減少重複,這通常是好做法,因為能讓後續維護更容易。

本練習屬於課程

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

檢視課程

練習說明

已將重複的資料篩選程式碼片段移除。你的任務是新增一個會篩選資料的 reactive 變數,並改用這個變數。具體要求如下:

  • 使用 reactive() 建立名為 filtered_data 的 reactive 變數,內容使用上一個練習的篩選程式碼(第 15 行)。
  • 使用這個 reactive 變數來產生表格輸出、繪圖輸出,以及下載的檔案(第 33、42 與 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))),
  downloadButton(outputId = "download_data", label = "Download"),
  plotOutput("plot"),
  tableOutput("table")
)

server <- function(input, output) {
  # Create a reactive variable named "filtered_data"
  filtered_data <- ___({
    # Filter the data (copied from previous exercise)
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    if (input$continent != "All") {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    data
  })
  
  output$table <- renderTable({
    # Use the filtered_data variable to render the table output
    data <- ___
    data
  })

  output$download_data <- downloadHandler(
    filename = "gapminder_data.csv",
    content = function(file) {
      # Use the filtered_data variable to create the data for
      # the downloaded file
      data <- ___
      write.csv(data, file, row.names = FALSE)
    }
  )

  output$plot <- renderPlot({
    # Use the filtered_data variable to create the data for
    # the plot
    data <- ___
    ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point() +
      scale_x_log10()
  })
}

shinyApp(ui, server)
編輯並執行程式碼