หยุดสร้าง word cloud ใหม่ตลอดเวลา
ตอนนี้แอป word cloud มี input หลายรายการ และการแก้ไข input แต่ละอย่างจะทำให้ word cloud วาดใหม่ด้วยพารามิเตอร์ที่อัปเดต ซึ่งเป็นพฤติกรรมที่คาดหวัง
อย่างไรก็ตาม พฤติกรรมนี้อาจสร้างความรำคาญได้ในบางกรณี ตัวอย่างเช่น เมื่อพิมพ์ข้อความในพื้นที่ textarea word cloud จะสร้างใหม่ตลอดเวลาโดยไม่รอให้พิมพ์เสร็จ ซึ่งสามารถควบคุมได้ด้วย isolate()
โค้ดทั้งหมดภายใน renderWordcloud2() ที่ใช้เรนเดอร์ word cloud ถูกลบออกแล้ว งานของคุณคือสร้าง word cloud ขึ้นมาใหม่และ isolate ไว้ เพื่อให้การเปลี่ยนพารามิเตอร์ไม่ทำให้ word cloud สร้างใหม่โดยอัตโนมัติ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R
คำแนะนำการฝึกหัด
- ตรวจสอบให้แน่ใจว่าฟังก์ชันสร้าง word cloud ทั้งหมดถูก isolate ไว้ (บรรทัดที่ 54)
- ระบุอาร์กิวเมนต์ให้กับ
create_wordcloud()โดยใช้ input และตัวแปร reactive ที่จำเป็น อาร์กิวเมนต์ของฟังก์ชันได้แก่data,num_wordsและbackground(บรรทัดที่ 56)
ผลลัพธ์ที่ได้อาจดูเหมือนแอปทำงานผิดปกติ เนื่องจากจะไม่สามารถสร้าง word cloud ใหม่ได้ แต่ปัญหานี้จะได้รับการแก้ไขในแบบฝึกหัดถัดไป
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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)