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

การสร้าง output object

มีกฎ 3 ข้อในการสร้าง output ใน Shiny:

  1. สร้าง object ด้วยฟังก์ชัน render*() ที่เหมาะสม

  2. บันทึกผลลัพธ์ของฟังก์ชัน render ลงใน list ชื่อ output ซึ่งเป็น parameter ของฟังก์ชัน server โดยเฉพาะอย่างยิ่ง ให้บันทึกลงใน output$<outputId> เพื่อแทนที่ output placeholder ใน UI ที่มี ID เป็น outputId

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