開始使用免費開始

有條件地顯示或隱藏必要的輸入元件

這個文字雲應用現在有三種不同方式可提供要產生文字雲的文字。其中有兩種方式會用到只對它們有用的特定 UI 元件:當使用者選擇「own」來源時才會用到的多行文字輸入區(textarea),以及當使用者選擇「file」來源時才相關的檔案上傳輸入。理想情況下,任何時間點只顯示需要的輸入元件。

本練習屬於課程

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

檢視課程

練習說明

多行文字輸入區已經包在 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)
編輯並執行程式碼