始める無料で始める

Don't continuously create new word clouds

The word cloud app now has several different inputs, and modifying each one of them causes the word cloud to redraw with the new set of parameters, just as expected.

But this behaviour can also be annoying sometimes. For example, when typing text in the textarea, the word cloud keeps regenerating without waiting for you to finish typing. This can be controlled with isolate().

All the code inside renderWordcloud2() that renders the word cloud has been removed. Your task is to re-create the word cloud and isolate it so that changing the parameters will not automatically trigger a new word cloud.

この演習はコースの一部です

Case Studies: Building Web Applications with Shiny in R

コースを見る

演習の手順

  • Ensure the entire word cloud generating function is isolated (line 54).
  • Supply the arguments to create_wordcloud() using the necessary inputs and reactive variables. The arguments for the function are data, num_words, and background (line 56).

The result of this may seem like the app is broken because you will not be able to create a new word cloud, but that will be addressed in a following exercise.

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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")
    ),
    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({
    # Isolate the code to render the word cloud so that it will
    # not automatically re-render on every parameter change
    ___({
      # Render the word cloud using inputs and reactives
      create_wordcloud(data = ___, num_words = ___,
                       background = ___)
    })
  })
}

shinyApp(ui = ui, server = server)
コードを編集して実行