r 闪亮:将 dateInput 与 shinjs::toggleState 一起使用时无法解决错误

r Shiny: Cannot resolve error when using dateInput with shinjs::toggleState

我正在使用 R 版本 3.6.2,在 shinyjs::toggleState 中使用 dateInput 时遇到错误。我的代码的错误不会为其他输入数据类型生成。我觉得我在日期转换的某个阶段犯了错误。我尝试了几种不同的选择,但仍然无法解决问题。非常感谢任何解决问题的支持。 UI 的片段和我尝试的服务器代码如下。

尝试 1

UI

 shinyjs::useShinyjs(),
    selectInput("player_names_output","Select Player",choices = c("Player 1","Player 2","Player 3")),
     dateInput("session_date", "Training Date",value = as.Date(NA),format = "%d-%m-%Y"),
    actionButton("submit_button","Submit"),

服务器

   observe({
      shinyjs::toggleState("submit_button", !is.null(input$player_names) && input$player_names != "" && !is.null(input$session_date) && input$session_date != "")
    })

Error in charToDate: character string is not in a standard unambiguous format

尝试 2

UI

shinyjs::useShinyjs(),
selectInput("player_names_output","Select Player",choices = c("Player 1","Player 2","Player 3")),
 dateInput("session_date", "Training Date",value = as.Date(NA),format = "%d-%m-%Y"),
actionButton("submit_button","Submit"),

服务器

 observe({
      shinyjs::toggleState("submit_button", !is.null(input$player_names) && input$player_names != "" && 
   !is.null(as.Date(input$session_date,format = "%d-%m-%Y")) && as.Date(input$session_date,format = "%d- 
     %m-%Y") != "")
    })

Error in charToDate: character string is not in a standard unambiguous format

非常感谢

不需要ui中的as.Date,将日期格式传递给dateInputformat参数。然后将日期对象传递给 value 或将与传递给 format 参数的格式相同的字符串传递给值。

将此放入您的 ui:

shinyjs::useShinyjs(),
selectInput("player_names_output","Select Player",choices = c("Player 1","Player 2","Player 3")),
dateInput("session_date", "Training Date",value = Sys.Date(), format = "dd-mm-yyyy"),  actionButton("submit_button","Submit")

发生错误是因为您试图将日期与服务器中的字符串进行比较。你只能比较同类。将 input$session_date 放在 as.character() 调用中。此外,默认情况下,日期输入将是一个日期对象,因此无需在服务器中使用 as.Date

更新服务器:

server <- function(input, output, session) {
  observe({
    shinyjs::toggleState("submit_button", condition = !is.null(input$player_names) & input$player_names != "" &
                           !is.null(input$session_date) & as.character(input$session_date) != "")
  })
}

shinyApp(ui, server)