驗證使用者是否已做出選擇
回想影片中的內容:雖然為選擇器輸入設定預設值通常是好做法,但如果不想設定預設值,你可以拋出自訂錯誤訊息,提示使用者需要做什麼,才能讓應用程式順利執行。
在前一個練習中我們看到,若 pickerInput() 沒有預設值,圖形就會是空白。這一題要改成不要顯示空白圖,而是顯示自訂錯誤訊息,告訴使用者需要做出正確的選擇,才能讓應用程式運作。
本練習屬於課程
使用 R 的 Shiny 建立網頁應用程式
練習說明
- 新增一則自訂錯誤訊息,預設就會顯示,提醒使用者需要選擇「心理健康」或「身體健康」作為輸入。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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)