开始使用免费开始使用

按需显示或隐藏必需输入

这个词云应用现在支持 3 种方式向词云提供词汇。其中两种方式各自需要一个只对该方式有用的 UI 元素:当用户选择 "own" 作为词源时,才会用到一个多行文本框;当用户选择 "file" 作为词源时,才会用到一个文件输入。理想情况下,任意时刻只显示当前所需的输入控件。

本练习是课程的一部分

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

查看课程

练习说明

多行文本框已经被包在 conditionalPanel() 中,因此只有当用户选择输入自定义文本时才会显示。您的任务是:仅在用户选择文件上传作为数据源时,按条件显示文件输入。具体要求:

  • 用一个条件面板包裹文件输入(第 19 行)。
  • 当用户在数据源单选按钮中选择 "file" 选项时(第 22 行),该面板的条件应被满足。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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)
      ),
      # Wrap the file input in a conditional panel
      ___(
        # The condition should be that the user selects
        # "file" from the radio buttons
        condition = ___,
        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({
    create_wordcloud(data_source(), num_words = input$num,
                        background = input$col)
  })
}

shinyApp(ui = ui, server = server)
编辑并运行代码