เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

เลือกแหล่งข้อมูล (ui)

ในแบบฝึกหัดที่ผ่านมา คุณได้ใช้แหล่งข้อมูล 3 รูปแบบสำหรับ word cloud ได้แก่ หนังสือ Art of War, ช่องข้อความ และไฟล์ข้อความ แต่ในแต่ละครั้งจะใช้ได้เพียงแหล่งเดียวเท่านั้น ในแบบฝึกหัดนี้ คุณจะเพิ่มตัวเลือกให้ผู้ใช้สามารถเลือกแหล่งข้อมูลที่ต้องการใช้สำหรับ word cloud ได้

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

ดูคอร์ส

คำแนะนำการฝึกหัด

เพิ่มปุ่มตัวเลือก (radio buttons) ลงในแอป เพื่อให้ผู้ใช้เลือกว่าจะใช้แหล่งข้อความจากหนังสือ Art of War, ช่องข้อความ หรือไฟล์ที่อัปโหลด โดยมีรายละเอียดดังนี้:

  • เพิ่ม radio buttons input ที่มี label ว่า "Word source" และมีตัวเลือก 3 รายการ:
    • ค่าของตัวเลือกควรเป็น "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)
แก้ไขและรันโค้ด