Create a new word cloud on demand
After isolating the word cloud render code so that it wouldn't update too often, the last step is to provide a way to render the word cloud only when the user chooses to. This can be achieved with the help of an actionButton()
.
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
Your task is to add a button to the Shiny app, and re-render the word cloud when the button gets pressed. Specifically:
- Add an action button to the app with an input ID of "draw" and a label of "Draw!" (line 26).
- Add the button as a dependency in the word cloud rendering function so that the word cloud will re-run when the button is pressed (line 56).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
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)