shinyApp แรกของคุณ
ได้เห็นแล้วว่า input และ output สามารถนำมาประกอบกันใน shinyApp ได้อย่างไร รวมถึงวิธีสร้าง shinyApp เพื่อแสดงผลลัพธ์จากการศึกษาข้อมูลการนอนหลับ
คราวนี้ถึงเวลาสร้าง shinyApp เพื่อรายงานผลลัพธ์หลัก 2 รายการ:
- การกระจายของชั่วโมงการนอนหลับ
- ค่ามัธยฐานของชั่วโมงการนอนหลับในแต่ละกลุ่มอายุ
ในแบบฝึกหัดนี้ ข้อมูลถูกเก็บอยู่ใน data frame ของ dplyr ชื่อ sleep และโหลดไลบรารี shiny กับ tidyverse ไว้เรียบร้อยแล้ว
ถึงคิวของคุณแล้ว — ลองสร้าง shinyApp ของตัวเองดูได้เลย!
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การสร้างแดชบอร์ดด้วย shinydashboard
คำแนะนำการฝึกหัด
- เพิ่ม plot output 2 รายการชื่อ "histogram" และ "barchart" ลงใน
mainPanel - ในอาร์กิวเมนต์
choiceNamesของcheckboxGroupInput()ให้แทนที่เนื้อหาด้วยไอคอนชื่อ "calendar", "briefcase" และ "gift" - กำหนด output 2 รายการ ได้แก่
histogramและbarchart - ใช้ฟังก์ชัน
shinyApp()เพื่อเรนเดอร์ shiny app
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
ui <- fluidPage(
titlePanel("Sleeping habits in America"),
fluidRow(
# Place two plots here, called "histogram" and "barchart"
mainPanel(___("histogram"), ___("barchart")),
inputPanel(sliderInput("binwidth",
label = "Bin width",
min = 0.1, max = 2,
step = 0.01, value=0.25),
checkboxGroupInput("days", "Choose types of days:",
# Replace the list elements with icons called "calendar", "briefcase" and "gift"
choiceNames = list("All days",
"Non-holiday weekdays",
"Weekend days/holidays"),
choiceValues = list("All days",
"Nonholiday weekdays",
"Weekend days and holidays"))),
"In general, across the different age groups, Americans seem to get adequate daily rest." ))
server <- function(input, output, session) {
# Define the histogram and barchart
output$histogram <- ___({
ggplot(sleep, aes(x=`Avg hrs per day sleeping`)) +
geom_histogram(binwidth = input$binwidth, col='white') +
theme_classic()
})
___ <- ___({
filter(sleep, `Type of Days` %in% input$days) %>%
group_by(`Type of Days`, `Age Group`) %>%
summarize(`Median hours` = median(`Avg hrs per day sleeping`)) %>%
ggplot(aes(x = `Median hours`, y = `Age Group`, fill = `Type of Days`)) +
geom_col(position = 'dodge') + theme_classic()
})
}
# Use shinyApp() to render the shinyApp
___