開始使用免費開始

選擇資料來源(server)

在使用單選按鈕時,有時需要在 server 端以條件邏輯(if-else 敘述)來存取單選按鈕的值。當不同選項會觸發不同動作,且必須先檢視所選的值再決定後續流程時,就需要這樣做。

例如,當單選按鈕用來選擇資料來源時,會依據選到的選項來執行不同的程式碼。

你的下一個任務是:根據使用者選擇的單選按鈕,將正確的資料來源傳給文字雲函式。

本練習屬於課程

案例研究:使用 R 的 Shiny 建置網頁應用程式

檢視課程

練習說明

  • 定義名為 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)
編輯並執行程式碼