開始使用免費開始

選擇資料來源(ui)

在前幾個練習中,你用了 3 種不同的文字雲來源:孫子兵法(Art of War)這本書、文字欄位,以及文字檔。不過,同一時間只有一種來源能運作。這一題要讓使用者可以自行選擇要用哪一種資料來源來產生文字雲。

本練習屬於課程

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

檢視課程

練習說明

你的任務是替應用程式加入單選按鈕,讓使用者選擇文字來源要用孫子兵法(Art of War)這本書、文字區塊,或上傳的檔案。具體來說:

  • 新增一個標籤為「Word source」的單選按鈕輸入元件,且包含三個選項:
    • 選項的值應為「book」、「own」和「file」。顯示給使用者看的名稱分別為「Art of War」、「Use your own words」以及「Upload a file」。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

ui <- fluidPage(
  h1("Word Cloud"),
  sidebarLayout(
    sidebarPanel(
      # Add radio buttons input
      ___(
        inputId = "source",
        label = ___,
        choices = c(
          # First choice is "book", with "Art of War" displaying
          "Art of War" = "book",
          # Second choice is "own", with "Use your own words" displaying
          ___ = "own",
          # Third choice is "file", with "Upload a file" displaying
          ___ = ___
        )
      ),
      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) {
  input_file <- reactive({
    if (is.null(input$file)) {
      return("")
    }
    readLines(input$file$datapath)
  })

  output$cloud <- renderWordcloud2({
    create_wordcloud(input_file(), num_words = input$num,
                     background = input$col)
  })
}

shinyApp(ui = ui, server = server)
編輯並執行程式碼