开始使用免费开始使用

选择数据源(server)

在处理单选按钮时,服务器端在读取其取值时有时需要使用条件逻辑(if-else 语句)。当不同选项对应不同操作,需要先检查所选值再决定如何处理时,就必须这样做。

例如,对于用于选择数据源的单选按钮,不同的选项需要运行不同的代码。

接下来,您的任务是根据用户选择的单选按钮,在词云函数中使用相应的数据源。

本练习是课程的一部分

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

查看课程

练习说明

  • 定义名为 data_source 的响应式变量,用来保存将用于词云的数据(第 28 行)。
  • 若选择 "book" 选项("Art of War"),则将 artofwar 这本书作为数据源。若选择 "own" 选项("Use your own words"),则将多行文本框的内容作为数据源。若选择 "file" 选项("Upload a file"),则将用户上传文件中的文本作为数据源(第 33 至 36 行)。
  • 将响应式变量 data_source() 作为词云函数中 data 参数的取值(第 51 行)。

交互式实操练习

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

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"
        )
      ),
      textAreaInput("text", "Enter text", rows = 7),
      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) {
  # Create a "data_source" reactive variable
  data_source <- ___({
    # Return the appropriate data source depending on
    # the chosen radio button
    if (input$source == "book") {
      data <- artofwar
    } else if (input$source == ___) {
      data <- input$___
    } else if (___ == "file") {
      data <- input_file()
    }
    return(data)
  })

  input_file <- reactive({
    if (is.null(input$file)) {
      return("")
    }
    readLines(input$file$datapath)
  })

  output$cloud <- renderWordcloud2({
    # Use the data_source reactive variable as the data
    # in the word cloud function
    create_wordcloud(data = ___(), num_words = input$num,
                     background = input$col)
  })
}

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