开始使用免费开始使用

您的第一个 shinyApp

您已经看到如何在 shinyApp 中组合输入和输出。您也了解了如何构建一个 shinyApp 来呈现睡眠研究的结果。

现在,您的目标是创建一个 shinyApp 来报告两项主要结果:

  1. 睡眠时长的分布
  2. 不同年龄组的睡眠时长中位数

在本练习中,我们已将数据保存为名为 sleepdplyr 数据框,并且已经加载了 shinytidyverse 库。

现在轮到您来创建自己的 shinyApp 了!

本练习是课程的一部分

使用 shinydashboard 构建仪表板

查看课程

练习说明

  • mainPanel 中添加两个名为 "histogram" 和 "barchart" 的图形输出。
  • checkboxGroupInput()choiceNames 参数中,将其内容替换为名为 "calendar"、"briefcase" 和 "gift" 的图标。
  • 定义两个输出,一个名为 histogram,另一个名为 barchart
  • 使用 shinyApp() 函数来渲染该 shiny 应用。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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
___
编辑并运行代码