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

สร้าง Word Cloud ใหม่ตามต้องการ

หลังจากที่แยกโค้ดสำหรับ render word cloud ออกมาเพื่อไม่ให้อัปเดตบ่อยเกินไปแล้ว ขั้นตอนสุดท้ายคือการเพิ่มวิธีให้ผู้ใช้สามารถสั่ง render word cloud ได้เองตามต้องการ ซึ่งทำได้โดยใช้ actionButton()

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

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

ดูคอร์ส

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

ให้เพิ่มปุ่มลงในแอป Shiny และ render word cloud ใหม่เมื่อผู้ใช้กดปุ่มนั้น โดยมีรายละเอียดดังนี้

  • เพิ่ม action button ลงในแอป โดยกำหนด input ID เป็น "draw" และ label เป็น "Draw!" (บรรทัดที่ 26)
  • เพิ่มปุ่มเป็น dependency ในฟังก์ชัน render word cloud เพื่อให้ word cloud รันใหม่ทุกครั้งที่กดปุ่ม (บรรทัดที่ 56)

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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)
แก้ไขและรันโค้ด