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

Biến bảng thành dạng tương tác

Datatable từ gói DT thường là cách hiển thị dữ liệu tốt hơn trong Shiny so với bảng dựng sẵn. Bạn có thể chuyển bảng Shiny sang datatable chỉ với hai chỉnh sửa đơn giản: thay vì dùng tableOutput()renderTable(), bạn dùng DT::dataTableOutput()DT::renderDataTable(). Datatable có rất nhiều tùy chọn tùy biến, nhưng ở đây chúng ta sẽ không dùng tùy chọn đặc biệt nào.

Lưu ý: với gói DT, quy ước là không load gói DT, mà dùng tiền tố DT:: khi gọi các hàm datatable.

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

Mã cho ứng dụng Shiny từ bài tập trước được cung cấp nguyên vẹn, chưa chỉnh sửa. Nhiệm vụ của bạn là thay bảng Shiny cơ bản bằng bảng DT. Cụ thể:

  • Ở UI, thay hàm xuất bảng bằng hàm xuất datatable của DT (dòng 11).
  • Ở server, thay hàm render bảng bằng hàm render datatable của DT (dòng 31).

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("download_data"),
  plotOutput("plot"),
  # Replace the tableOutput() with DT's version
  tableOutput("table")
)

server <- function(input, output) {
  filtered_data <- reactive({
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    if (input$continent != "All") {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    data
  })
  
  # Replace the renderTable() with DT's version
  output$table <- renderTable({
    data <- filtered_data()
    data
  })

  output$download_data <- downloadHandler(
    filename = "gapminder_data.csv",
    content = function(file) {
      data <- filtered_data()
      write.csv(data, file, row.names = FALSE)
    }
  )

  output$plot <- renderPlot({
    data <- filtered_data()
    ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point() +
      scale_x_log10()
  })
}

shinyApp(ui, server)
Chỉnh sửa và Chạy Mã