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

Chọn nguồn dữ liệu (ui)

Trong các bài trước, bạn đã dùng 3 nguồn khác nhau cho đám mây từ: sách Art of War, một trường văn bản và một tệp văn bản. Tuy nhiên, mỗi lần chỉ có một nguồn hoạt động. Ở bài này, bạn sẽ cung cấp cho người dùng cách chọn nguồn dữ liệu dùng để tạo đám mây từ.

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 các nút radio vào ứng dụng để người dùng có thể chọn nguồn từ: sách Art of War, vùng nhập văn bản (textarea) hoặc tệp tải lên. Cụ thể:

  • Thêm một input nút radio với nhãn "Word source" có ba lựa chọn:
    • Giá trị của các lựa chọn lần lượt là "book", "own" và "file". Tên hiển thị cho người dùng lần lượt là "Art of War", "Use your own words" và "Upload a file".

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(
      # 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)
Chỉnh sửa và Chạy Mã