Bắt đầu ngayBắt đầu miễn phí

Biến reactive giúp giảm lặp mã

Trong các bài trước, đoạn mã lọc gapminder theo giá trị đầu vào bị lặp lại ba lần: một lần trong bảng, một lần trong biểu đồ và một lần trong trình xử lý tải xuống.

Biến Reactive có thể dùng để giảm trùng lặp mã — nhìn chung đây là một ý tưởng hay vì giúp việc bảo trì dễ dàng hơn.

Bài tập này là một phần của khóa học

Nghiên cứu tình huống: Xây dựng ứng dụng web với Shiny trong R

Xem khóa học

Hướng dẫn bài tập

Các khối mã lặp lại để lọc dữ liệu đã được loại bỏ. Nhiệm vụ của bạn là thêm một biến reactive để lọc dữ liệu và dùng biến này thay thế. Cụ thể:

  • Tạo một biến reactive tên filtered_data bằng hàm reactive() và dùng đoạn mã lọc từ bài trước (dòng 15).
  • Dùng biến reactive để render đầu ra bảng, đầu ra biểu đồ và tệp tải xuống (các dòng 33, 42 và 50).

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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)
Chỉnh sửa và Chạy Mã