Створюйте нову хмару слів за потреби
Після ізоляції коду рендерингу хмари слів, щоб він не оновлювався надто часто, останній крок — надати змогу створювати хмару слів лише тоді, коли користувач цього захоче. Це можна зробити за допомогою actionButton().
Ця вправа є частиною курсу
Case Studies: створення вебзастосунків із Shiny в R
Інструкції до вправи
Ваше завдання — додати кнопку до застосунку 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)