闪亮的去抖不渲染初始图

shiny debounce doesn't render initial plot

如果我向 get_data() 反应式表达式添加去抖动,则第一次检索数据时绘图不会呈现。但是,更改数据(通过选择新的 mpg)会导致绘图随后呈现。为什么是这样?有解决方法吗? 这是一个演示问题的简单最小示例。尝试删除 %>% debounce(500) 以查看它在没有它的情况下是否按预期工作:

if (interactive()) {
  options(device.ask.default = FALSE)

  library(shiny)
  library(magrittr)

  ui <- fluidPage(
    selectInput("select", label = "select mpg", choices = c(mtcars$mpg, ""), selected = ""),
    plotOutput("plot")
  )

  server <- function(input, output, session) {
    get_data <- reactive({
      req(input$select)
      mtcars[mtcars$mpg == input$select,]
      }) %>% debounce(500)

    get_plot <- reactive({
      data <- get_data()
      print(data)
      plot(get_data())
      }) 

      output$plot <- renderPlot({
        get_plot()
      })
  }

  shinyApp(ui, server)
}

这里发生了一些事情。我不认为我们被允许在 select 输入中有重复项。 mtcars$mpg 里面有重复的值。将初始值设置为 "" 也会导致奇怪的行为。如果您真的希望初始图与去抖一起为空,我们可以将其设置为 " "。这就是它的样子。

if (interactive()) {
  options(device.ask.default = FALSE)

  library(shiny)
  library(magrittr)

  ui <- fluidPage(
    selectInput("select", label = "select mpg", choices = c(" ",unique(mtcars$mpg)),selected = " "),
    plotOutput("plot")
  )

  server <- function(input, output, session) {
    get_data <- reactive({
      req(input$select)
      if(!is.na(as.numeric(input$select))) mtcars[mtcars$mpg == input$select,] else NULL
    }) %>% debounce(500)

    get_plot <- reactive({
      req(get_data())
      data <- get_data()
      print(data)
      plot(get_data())
    }) 

    output$plot <- renderPlot({
      get_plot()
    })
  }

  shinyApp(ui, server)
}

否则,如果您对初始情节没有意见,则可以进行以下工作。请注意使用 unique()

很重要
if (interactive()) {
  options(device.ask.default = FALSE)

  library(shiny)
  library(magrittr)

  ui <- fluidPage(
    selectInput("select", label = "select mpg", unique(mtcars$mpg)),
    plotOutput("plot")
  )

  server <- function(input, output, session) {
    get_data <- reactive({
      req(input$select)
      mtcars[mtcars$mpg == input$select,]
    }) %>% debounce(500)

    get_plot <- reactive({
      req(get_data())
      data <- get_data()
      print(data)
      plot(get_data())
    }) 

    output$plot <- renderPlot({
      get_plot()
    })
  }

  shinyApp(ui, server)
}

我什至尝试用 selectizeInput("select", label = "select mpg", choices = unique(mtcars$mpg),multiple = TRUE,options = list(maxItems = 1)) 替换 select 输入,这仍然导致问题。