시작하기무료로 시작하기

데이터 소스 선택(ui)

지난 몇 개의 연습 문제에서 워드 클라우드의 데이터 소스를 세 가지(책 Art of War, 텍스트 입력란, 텍스트 파일)로 사용해 보셨습니다. 하지만 한 번에 하나의 소스만 동작했죠. 이번 연습에서는 사용자가 워드 클라우드에 사용할 데이터 소스를 선택할 수 있도록 기능을 추가해 보겠습니다.

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

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

강의 보기

연습 안내

사용자가 단어 소스를 책 Art of War, 텍스트 영역, 업로드한 파일 중에서 선택할 수 있도록 라디오 버튼을 앱에 추가하세요. 구체적으로는:

  • 라벨이 "Word source"인 라디오 버튼 입력을 추가하고, 세 가지 선택지를 제공하세요:
    • 선택지의 값은 각각 "book", "own", "file"이어야 합니다. 사용자에게 표시될 이름은 각각 "Art of War", "Use your own words", "Upload a file"입니다.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

ui <- fluidPage(
  h1("Word Cloud"),
  sidebarLayout(
    sidebarPanel(
      # Add radio buttons input
      ___(
        inputId = "source",
        label = ___,
        choices = c(
          # First choice is "book", with "Art of War" displaying
          "Art of War" = "book",
          # Second choice is "own", with "Use your own words" displaying
          ___ = "own",
          # Third choice is "file", with "Upload a file" displaying
          ___ = ___
        )
      ),
      textAreaInput("text", "Enter text", rows = 7),
      fileInput("file", "Select a file"),
      numericInput("num", "Maximum number of words",
                   value = 100, min = 5),
      colourInput("col", "Background color", value = "white")
    ),
    mainPanel(
      wordcloud2Output("cloud")
    )
  )
)

server <- function(input, output) {
  input_file <- reactive({
    if (is.null(input$file)) {
      return("")
    }
    readLines(input$file$datapath)
  })

  output$cloud <- renderWordcloud2({
    create_wordcloud(input_file(), num_words = input$num,
                     background = input$col)
  })
}

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