开始使用免费开始使用

按需创建新的词云

在将词云的渲染代码隔离以避免过于频繁更新之后,最后一步是提供一种方式,只在用户选择时才渲染词云。这可以借助 actionButton() 实现。

本练习是课程的一部分

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

查看课程

练习说明

您的任务是向 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)
编辑并运行代码