เลือกแหล่งข้อมูล (server)
เมื่อทำงานกับ radio button บางครั้งต้องใช้ตรรกะแบบมีเงื่อนไข (คำสั่ง if-else) ในการเข้าถึงค่าของ radio button ฝั่ง server ซึ่งจำเป็นเมื่อต้องดำเนินการที่แตกต่างกันขึ้นอยู่กับตัวเลือกที่เลือก และต้องตรวจสอบค่านั้นก่อนจะตัดสินใจดำเนินการต่อ
ตัวอย่างเช่น สำหรับ radio button ที่ใช้เลือกแหล่งข้อมูล โค้ดที่รันจะแตกต่างกันไปตามตัวเลือกที่ผู้ใช้เลือก
ภารกิจถัดไปคือการนำแหล่งข้อมูลที่เหมาะสมมาใช้ในฟังก์ชันสร้าง word cloud ตามตัวเลือก radio button ที่ผู้ใช้เลือก
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R
คำแนะนำการฝึกหัด
- กำหนดตัวแปร reactive ชื่อ
data_sourceเพื่อเก็บข้อมูลที่จะใช้สร้าง word cloud (บรรทัดที่ 28) - ถ้าเลือกตัวเลือก "book" ("Art of War") ให้กำหนดหนังสือ
artofwarเป็นแหล่งข้อมูล ถ้าเลือกตัวเลือก "own" ("Use your own words") ให้กำหนดค่าจาก textarea เป็นแหล่งข้อมูล และถ้าเลือกตัวเลือก "file" ("Upload a file") ให้กำหนดข้อความจากไฟล์ที่ผู้ใช้อัปโหลดเป็นแหล่งข้อมูล (บรรทัดที่ 33 ถึง 36) - ใช้ตัวแปร reactive
data_source()เป็นอาร์กิวเมนต์dataในฟังก์ชันสร้าง word cloud (บรรทัดที่ 51)
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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"
)
),
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) {
# Create a "data_source" reactive variable
data_source <- ___({
# Return the appropriate data source depending on
# the chosen radio button
if (input$source == "book") {
data <- artofwar
} else if (input$source == ___) {
data <- input$___
} else if (___ == "file") {
data <- input_file()
}
return(data)
})
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
readLines(input$file$datapath)
})
output$cloud <- renderWordcloud2({
# Use the data_source reactive variable as the data
# in the word cloud function
create_wordcloud(data = ___(), num_words = input$num,
background = input$col)
})
}
shinyApp(ui = ui, server = server)