开始使用免费开始使用

不要持续不断地创建新词云

这个词云应用现在有多个不同的输入项。修改任意一个都会让词云按预期使用新的参数重新绘制。

不过,这种行为有时会让人困扰。比如在文本区域中输入内容时,词云会不停地重新生成,而不会等待您输入完成。可以使用 isolate() 来控制这一点。

renderWordcloud2() 中用于渲染词云的所有代码已被移除。您的任务是重新创建词云,并将其隔离,这样当参数变化时就不会自动触发新的词云。

本练习是课程的一部分

案例研究:使用 R 的 Shiny 构建 Web 应用

查看课程

练习说明

  • 确保整个生成词云的函数被隔离(第 54 行)。
  • 使用所需的输入和响应式变量为 create_wordcloud() 提供参数。该函数的参数为 datanum_wordsbackground(第 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")
    ),
    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)
编辑并运行代码