시작하기무료로 시작하기

표를 인터랙티브하게 만들기

DT 패키지의 Datatable은 기본 제공 표보다 Shiny 앱에서 데이터를 표시하기에 더 나은 경우가 많습니다. Shiny 표는 간단한 두 가지 코드 변경만으로 datatable로 바꿀 수 있어요. tableOutput()renderTable() 대신 DT::dataTableOutput()DT::renderDataTable()을 사용하면 됩니다. Datatable은 매우 다양한 커스터마이즈 옵션을 제공하지만, 여기서는 특별한 옵션을 사용하지 않겠습니다.

DT 패키지 사용 시의 관례로, 패키지를 로드하지 않고 datatable 함수를 호출할 때 DT:: 접두사를 붙이는 방식을 권장합니다.

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

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

강의 보기

연습 안내

이전 코딩 연습 문제에서 만들었던 Shiny 앱 코드가 수정 없이 제공됩니다. 기본 Shiny 표를 DT 표로 바꾸세요. 구체적으로는 다음을 수행하세요.

  • UI에서 표 출력 함수를 DT의 datatable 출력으로 바꾸세요(11행).
  • 서버에서 표 렌더링 함수를 DT의 datatable 렌더 함수로 바꾸세요(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)
코드 편집 및 실행