시작하기무료로 시작하기

필터링된 데이터 다운로드

파일 다운로드는 downloadButton()downloadHandler()라는 두 함수 쌍으로 구현합니다. 이 두 함수는 출력 함수와 렌더 함수가 짝을 이루는 방식과 비슷하게 동작해요. downloadButton()은 UI에서 버튼이 표시될 위치를 정하고, downloadHandler()는 실제로 다운로드할 파일을 만드는 R 코드를 포함하여 output 리스트에 저장되어야 합니다.

이 연습은 강의의 일부입니다

사례 연구: R의 Shiny로 웹 애플리케이션 만들기

강의 보기

연습 안내

현재 테이블에서 보고 있는 데이터를 CSV 파일로 다운로드할 수 있도록 기능을 추가하세요. 구체적으로:

  • ID가 "download_data"이고 레이블이 "Download"인 다운로드 버튼을 UI에 추가하세요.
  • 서버에 다운로드 핸들러를 추가하세요(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)
코드 편집 및 실행