시작하기무료로 시작하기

반응형 변수로 중복 코드 줄이기

이전 연습 문제들에서는 입력값에 따라 gapminder를 필터링하는 코드가 표, 그래프, 그리고 다운로드 핸들러에서 각각 한 번씩, 총 세 번 중복되어 있습니다.

Reactive 변수를 사용하면 이런 중복을 줄일 수 있습니다. 일반적으로 유지 보수를 쉽게 하므로 좋은 방법입니다.

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

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

강의 보기

연습 안내

데이터를 필터링하던 중복된 코드 조각은 제거되어 있습니다. 이제 데이터를 필터링하는 반응형 변수를 추가하고, 그 변수를 대신 사용하세요. 구체적으로:

  • 이전 연습 문제의 필터링 코드를 활용해 reactive() 함수를 사용하여 filtered_data라는 반응형 변수를 만드세요(15행).
  • 이 반응형 변수를 사용해 표 출력, 그래프 출력, 그리고 다운로드 파일을 생성하세요(33, 42, 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))),
  downloadButton(outputId = "download_data", label = "Download"),
  plotOutput("plot"),
  tableOutput("table")
)

server <- function(input, output) {
  # Create a reactive variable named "filtered_data"
  filtered_data <- ___({
    # Filter the data (copied from previous exercise)
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    if (input$continent != "All") {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    data
  })
  
  output$table <- renderTable({
    # Use the filtered_data variable to render the table output
    data <- ___
    data
  })

  output$download_data <- downloadHandler(
    filename = "gapminder_data.csv",
    content = function(file) {
      # Use the filtered_data variable to create the data for
      # the downloaded file
      data <- ___
      write.csv(data, file, row.names = FALSE)
    }
  )

  output$plot <- renderPlot({
    # Use the filtered_data variable to create the data for
    # the plot
    data <- ___
    ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point() +
      scale_x_log10()
  })
}

shinyApp(ui, server)
코드 편집 및 실행