Bắt đầu ngayBắt đầu miễn phí

Tạo word cloud mới khi cần

Sau khi cô lập đoạn mã render word cloud để tránh cập nhật quá thường xuyên, bước cuối cùng là cung cấp cách chỉ render word cloud khi người dùng muốn. Bạn có thể làm điều này với actionButton().

Bài tập này là một phần của khóa học

Nghiên cứu tình huống: Xây dựng ứng dụng web với Shiny trong R

Xem khóa học

Hướng dẫn bài tập

Nhiệm vụ của bạn là thêm một nút vào ứng dụng Shiny và render lại word cloud khi nút được nhấn. Cụ thể:

  • Thêm một action button vào ứng dụng với input ID là "draw" và nhãn là "Draw!" (dòng 26).
  • Thêm nút này làm phụ thuộc trong hàm render word cloud để word cloud chạy lại khi nút được nhấn (dòng 56).

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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)
      ),
      conditionalPanel(
        condition = "input.source == 'file'",
        fileInput("file", "Select a file")
      ),
      numericInput("num", "Maximum number of words",
                   value = 100, min = 5),
      colourInput("col", "Background color", value = "white"),
      # Add a "draw" button to the app
      ___(inputId = ___, label = ___)
    ),
    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({
    # Add the draw button as a dependency to
    # cause the word cloud to re-render on click
    input$___
    isolate({
      create_wordcloud(data_source(), num_words = input$num,
                       background = input$col)
    })
  })
}

shinyApp(ui = ui, server = server)
Chỉnh sửa và Chạy Mã