开始使用免费开始使用

验证用户是否已进行选择

请回忆视频中的内容:通常为选择型输入设置一个默认值是个好做法,但如果需要强制用户做出选择,您可以抛出一条自定义错误消息,让用户明确需要怎么做才能让应用成功运行。

在上一个练习中我们看到,如果 pickerInput() 没有默认值,图形会是空白。本练习中,您将不再显示空白图,而是向用户显示一条自定义错误消息,提示他们做出正确选择,以便应用正常工作。

本练习是课程的一部分

使用 R 构建 Shiny Web 应用

查看课程

练习说明

  • 添加一条自定义错误消息,默认显示,告知用户应选择心理健康或身体健康对应的输入。

交互式实操练习

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

ui <- fluidPage(
  titlePanel("2014 Mental Health in Tech Survey"),
  sidebarPanel(
    sliderTextInput(
      inputId = "work_interfere",
      label = "If you have a mental health condition, do you feel that it interferes with your work?", 
      grid = TRUE,
      force_edges = TRUE,
      choices = c("Never", "Rarely", "Sometimes", "Often")
    ),
    checkboxGroupInput(
      inputId = "mental_health_consequence",
      label = "Do you think that discussing a mental health issue with your employer would have negative consequences?", 
      choices = c("Maybe", "Yes", "No"),
      selected = "Maybe"
    ),
    pickerInput(
      inputId = "mental_vs_physical",
      label = "Do you feel that your employer takes mental health as seriously as physical health?", 
      choices = c("Don't Know", "No", "Yes"),
      multiple = TRUE
    )    
  ),
  mainPanel(
    plotOutput("age")  
  )
)

server <- function(input, output, session) {
  output$age <- renderPlot({
    # MODIFY CODE BELOW: Add validation that user selected a 3rd input
    
    
    
    
    
    

    mental_health_survey %>%
      filter(
        work_interfere == input$work_interfere,
        mental_health_consequence %in% input$mental_health_consequence,
        mental_vs_physical %in% input$mental_vs_physical
      ) %>%
      ggplot(aes(Age)) +
      geom_histogram()
  })
}

shinyApp(ui, server)
编辑并运行代码