R语言 在选择日期和selectInput之后更新selectInput

kpbwa7wx  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(163)

我想调整我的第二个selectInput(market)。请注意,当在日历中选择星期日或星期二时,会出现相应的轮班,在本例中为Morning或Evening。这些值考虑了来自df1数据库的信息。因此,例如,如果我在日历中选择星期日,然后选择Morning轮班,我希望它在第二个selectInput中显示星期天上午工作的市场,在本例中是Market1和Market2。

library(shiny)
library(shinythemes)
library(lubridate)

df1<- structure(
  list(
    Marketname = c("Market1","Market1", "Market2","Market2", "Market3", "Market3"),
    Days = c("Sunday","Sunday","Sunday","Sunday", "Sunday","Tuesday"),
    Openinghours = c("Morning","Evening", "Morning","Evening","Evening","Evening")
  ), row.names = c(NA, 6L), class = "data.frame")

ui <- fluidPage(  
  shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
                    br(),
                    tabPanel("",
                             sidebarLayout(
                               sidebarPanel(
                                 dateInput("date", "Which day shift do you choose?"),
                                 selectInput("hours", label = h5("Which work shift do you choose??"), choices = NULL, 
                                             selected = ""),
                                 selectInput("market", label = h5("Choose a market??"), choices = NULL, 
                                             selected = "")
                               ),
                               mainPanel(
                               )
                             ))
  ))

server <- function(input, output,session) {
  
  observe({
    week_day <- wday(input$date, label = TRUE, abbr = FALSE)
    
    updateSelectInput(session, "hours", choices = unique(df1[df1$Days == week_day, 3]))
  })
}

shinyApp(ui = ui, server = server)
6gpjuf90

6gpjuf901#

您可以使用第二个observe r。
注意:我还添加了一个reactive来存储工作日,它可以在两个观察者中使用。

server <- function(input, output, session) {
  week_day <- reactive({
    wday(input$date, label = TRUE, abbr = FALSE, locale = "en_US")
  })
  
  observe({
    updateSelectInput(session, "hours",
      choices = unique(df1[df1$Days == week_day(), "Openinghours"])
    )
  })

  observe({
    updateSelectInput(session, "market",
      choices = unique(df1[df1$Days == week_day() & df1$Openinghours %in% input$hours, "Marketname"])
    )
  })
}

相关问题