shinyApp đầu tiên của bạn
Bạn đã thấy cách ghép các input và output trong một shinyApp, và cách xây dựng một shinyApp để truyền đạt kết quả từ nghiên cứu về giấc ngủ.
Mục tiêu của bạn bây giờ là tạo một shinyApp để báo cáo hai kết quả chính:
- Phân phối số giờ ngủ
- Số giờ ngủ trung vị theo các nhóm tuổi khác nhau
Trong bài tập này, dữ liệu đã được lưu dưới dạng một data frame dplyr tên là sleep, và các thư viện shiny và tidyverse đã được nạp sẵn.
Giờ đến lượt bạn tạo shinyApp của riêng mình!
Bài tập này là một phần của khóa học
Xây dựng Dashboard với shinydashboard
Hướng dẫn bài tập
- Thêm hai đầu ra biểu đồ có tên "histogram" và "barchart" vào
mainPanel. - Trong đối số
choiceNamescủacheckboxGroupInput(), thay nội dung bằng các icon có tên "calendar", "briefcase" và "gift". - Định nghĩa hai output, một tên
histogram, và một tênbarchart. - Dùng hàm
shinyApp()để render ứng dụng shiny.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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
___