首页 > 解决方案 > 在 Shiny 中,等待用户停止使用 rhandsontable 填充表格

问题描述

考虑到用户手动填写 a rhandsontable,我想实现一个与时间相关的条件来进行表格分析和绘图。例如,如果在最后 2 秒内没有任何内容添加到表中,则继续,否则等待 2 秒过去。

我尝试了validate()或简单的条件(如下所示)。它不起作用,因为observe()在修改表后立即访问,当时与时间相关的条件是false。当条件应为时,不再访问true该函数,因此不测试条件...observe()

我试图提供一个 MRE,但在一个简单的例子中我很难捍卫对这种功能的需求。需要与分析和绘图的计算时间有关。

library(shiny)
library(rhandsontable)
library(ggplot2)


DF <- data.frame(x=integer(0), y=integer(0))

ui <- shinyUI(fluidPage(
  mainPanel( 
    rHandsontableOutput("hot"),
    plotOutput("plot1")
  )
))


server <- shinyServer(function(input, output) {

  values <- reactiveValues()
  values$table <- DF
  values$accessDF <- 0

  observe({
    if (!is.null(input$hot)) {
      DF <- hot_to_r(input$hot)
      values$accessDF <- Sys.time() # reset awaiting time when table is incremented
    } else {
      if (is.null(values[["DF"]]))
        DF <- DF
      else
        DF <- values[["DF"]]
    }
    values[["DF"]] <- DF
  })

  output$hot <- renderRHandsontable({
    rhandsontable(values[["DF"]], stretchH = "all", minRows=5)
  })

  observe({

    if (Sys.time() - values$accessDF > 2){ # unfornate try...
      # some modification of the table occuring here
      values$table <- values$DF
    }

  })

  output$plot1 <- renderPlot({

    ggplot(data=values$table) + geom_line(aes(x=x, y=y))

  })

})

shinyApp(ui=ui, server=server)

标签: rshinyhandsontablerhandsontable

解决方案


我找到了一种解决方案。用于reactiveTimer()强制observe()激活即使它观察到的变量没有被更新。

server:

autoInvalidate <- reactiveTimer(200) # to activate observer every 200 ms

然后在observe()

autoInvalidate()

其次是条件

if (Sys.time() - values$accessDF > 2){ # unfornate try...
  # some modification of the table occuring here
  values$table <- values$DF
}

https://shiny.rstudio.com/reference/shiny/1.0.0/reactiveTimer.html


推荐阅读