เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ทำให้ตารางเป็นแบบโต้ตอบได้

Datatable จากแพ็กเกจ DT มักเป็นวิธีที่ดีกว่าในการแสดงข้อมูลใน Shiny app เมื่อเทียบกับตารางแบบมาตรฐาน การแปลงตาราง Shiny ให้เป็น datatable ทำได้ด้วยการแก้ไขโค้ดเพียง 2 จุด คือแทนที่ tableOutput() และ renderTable() ด้วย DT::dataTableOutput() และ DT::renderDataTable() ตามลำดับ Datatable มีตัวเลือกปรับแต่งหลากหลาย แต่ในแบบฝึกหัดนี้จะยังไม่ใช้ตัวเลือกพิเศษใดๆ

สังเกตว่าสำหรับแพ็กเกจ DT นั้น แบบแผนที่ใช้กันคือไม่โหลดแพ็กเกจ DT โดยตรง แต่ใช้ prefix DT:: เมื่อเรียกฟังก์ชัน datatable แทน

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

ดูคอร์ส

คำแนะนำการฝึกหัด

โค้ด Shiny app จากแบบฝึกหัดก่อนหน้าถูกเตรียมไว้ให้โดยไม่มีการแก้ไขใดๆ ให้แทนที่ตาราง Shiny แบบพื้นฐานด้วยตาราง DT โดยทำตามขั้นตอนต่อไปนี้

  • ใน UI ให้แทนที่ฟังก์ชัน table output ด้วย DT datatable output (บรรทัดที่ 11)
  • ใน server ให้แทนที่ฟังก์ชัน table rendering ด้วย DT datatable render function (บรรทัดที่ 31)

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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)
แก้ไขและรันโค้ด