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

Đừng liên tục tạo word cloud mới

Ứng dụng word cloud hiện có vài đầu vào khác nhau, và việc thay đổi mỗi đầu vào sẽ khiến word cloud vẽ lại với bộ tham số mới, đúng như mong đợi.

Nhưng đôi khi hành vi này cũng gây khó chịu. Ví dụ, khi gõ văn bản trong textarea, word cloud liên tục được tạo lại mà không chờ bạn gõ xong. Bạn có thể kiểm soát điều này với isolate().

Toàn bộ mã bên trong renderWordcloud2() dùng để vẽ word cloud đã được gỡ bỏ. Nhiệm vụ của bạn là tạo lại word cloud và cô lập nó để việc thay đổi tham số sẽ không tự động kích hoạt một word cloud mới.

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

  • Đảm bảo toàn bộ hàm tạo word cloud được đặt trong isolate (dòng 54).
  • Truyền các đối số cho create_wordcloud() bằng các input và biến reactive cần thiết. Các đối số của hàm là data, num_words, và background (dòng 56).

Kết quả có thể trông như ứng dụng bị hỏng vì bạn sẽ chưa thể tạo word cloud mới, nhưng điều đó sẽ được xử lý ở bài tập sau.

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")
    ),
    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({
    # Isolate the code to render the word cloud so that it will
    # not automatically re-render on every parameter change
    ___({
      # Render the word cloud using inputs and reactives
      create_wordcloud(data = ___, num_words = ___,
                       background = ___)
    })
  })
}

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