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

ดาวน์โหลดข้อมูลที่กรองแล้ว

การดาวน์โหลดไฟล์ทำได้โดยใช้ฟังก์ชันคู่ downloadButton() และ downloadHandler() ฟังก์ชันทั้งสองทำงานร่วมกันในลักษณะเดียวกับที่ฟังก์ชัน output และ render ทำงานคู่กัน กล่าวคือ downloadButton() กำหนดตำแหน่งที่ปุ่มจะแสดงใน UI ส่วน downloadHandler() ต้องบันทึกลงใน list output และมีโค้ด R สำหรับสร้างไฟล์ที่จะดาวน์โหลด

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

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

ดูคอร์ส

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

เพิ่มความสามารถในการดาวน์โหลดข้อมูลที่แสดงอยู่ในตารางเป็นไฟล์ CSV โดยดำเนินการดังนี้

  • เพิ่มปุ่มดาวน์โหลดใน UI โดยกำหนด ID เป็น "download_data" และ label เป็น "Download"
  • เพิ่ม download handler ในส่วน server (บรรทัดที่ 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)
แก้ไขและรันโค้ด