การสร้าง output object
มีกฎ 3 ข้อในการสร้าง output ใน Shiny:
สร้าง object ด้วยฟังก์ชัน
render*()ที่เหมาะสมบันทึกผลลัพธ์ของฟังก์ชัน render ลงใน list ชื่อ
outputซึ่งเป็น parameter ของฟังก์ชัน server โดยเฉพาะอย่างยิ่ง ให้บันทึกลงในoutput$<outputId>เพื่อแทนที่ output placeholder ใน UI ที่มี ID เป็นoutputIdหาก output นั้นขึ้นอยู่กับค่าอินพุตที่ผู้ใช้ปรับเปลี่ยน สามารถเข้าถึงอินพุตต่าง ๆ ได้ผ่าน parameter
inputของฟังก์ชัน server โดยinput$<inputId>จะคืนค่าปัจจุบันของฟิลด์อินพุตที่มี ID เป็นinputIdเสมอ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R
คำแนะนำการฝึกหัด
โจทย์กำหนด Shiny app ที่มีส่วน UI ทำงานได้อย่างสมบูรณ์แล้ว ให้สร้าง output ทั้งหมดดังนี้:
- สร้างกราฟจากชุดข้อมูล
carsใน output placeholder ของกราฟที่มี ID "cars_plot" (บรรทัดที่ 23) - ใน text output ชื่อ "greeting" ให้เรนเดอร์ข้อความทักทายในรูปแบบ "Hello NAME" โดยที่ NAME คือค่าของอินพุต name (บรรทัดที่ 28)
- ใน output ชื่อ "iris_table" ให้แสดงตารางของ n แถวแรกจากชุดข้อมูล
irisโดยที่ n คือค่าของอินพุตตัวเลข (บรรทัดที่ 33)
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Load the shiny package
library(shiny)
# Define UI for the application
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("name", "What is your name?", "Dean"),
numericInput("num", "Number of flowers to show data for",
10, 1, nrow(iris))
),
mainPanel(
textOutput("greeting"),
plotOutput("cars_plot"),
tableOutput("iris_table")
)
)
)
# Define the server logic
server <- function(input, output) {
# Create a plot of the "cars" dataset
output$cars_plot <- render___({
plot(cars)
})
# Render a text greeting as "Hello "
output$greeting <- ___({
paste("Hello", ___)
})
# Show a table of the first n rows of the "iris" data
___ <- ___({
data <- iris[1:input$num, ]
data
})
}
# Run the application
shinyApp(ui = ui, server = server)