원할 때 새 워드 클라우드 만들기
워드 클라우드 렌더링 코드를 자주 업데이트되지 않도록 분리했다면, 마지막 단계는 사용자가 선택할 때만 워드 클라우드를 렌더링하는 방법을 제공하는 것입니다. 이는 actionButton()의 도움으로 구현할 수 있습니다.
이 연습은 강의의 일부입니다
사례 연구: R의 Shiny로 웹 애플리케이션 만들기
연습 안내
이제 Shiny 앱에 버튼을 추가하고, 버튼이 눌릴 때 워드 클라우드를 다시 렌더링하세요. 구체적으로는 다음을 수행합니다.
- 입력 ID가 "draw"이고 라벨이 "Draw!"인 액션 버튼을 앱에 추가하세요(26행).
- 워드 클라우드 렌더링 함수에서 버튼을 의존성으로 등록해, 버튼이 눌릴 때 워드 클라우드가 다시 실행되도록 하세요(56행).
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
ui <- fluidPage(
h1("Word Cloud"),
sidebarLayout(
sidebarPanel(
radioButtons(
inputId = "source",
label = "Word source",
choices = c(
"Art of War" = "book",
"Use your own words" = "own",
"Upload a file" = "file"
)
),
conditionalPanel(
condition = "input.source == 'own'",
textAreaInput("text", "Enter text", rows = 7)
),
conditionalPanel(
condition = "input.source == 'file'",
fileInput("file", "Select a file")
),
numericInput("num", "Maximum number of words",
value = 100, min = 5),
colourInput("col", "Background color", value = "white"),
# Add a "draw" button to the app
___(inputId = ___, label = ___)
),
mainPanel(
wordcloud2Output("cloud")
)
)
)
server <- function(input, output) {
data_source <- reactive({
if (input$source == "book") {
data <- artofwar
} else if (input$source == "own") {
data <- input$text
} else if (input$source == "file") {
data <- input_file()
}
return(data)
})
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
readLines(input$file$datapath)
})
output$cloud <- renderWordcloud2({
# Add the draw button as a dependency to
# cause the word cloud to re-render on click
input$___
isolate({
create_wordcloud(data_source(), num_words = input$num,
background = input$col)
})
})
}
shinyApp(ui = ui, server = server)