R闪亮观察行取消选择数据表

R shiny observe for row deselection dataTable

我有一个闪亮的应用程序 DT::renderDataTable,用户可以 select 数据表中的一行。

下面的代码只会打印 FALSE(当一行被 selected 时):

observeEvent(input$segment_library_datatable_rows_selected, {
  print(is.null(input$segment_library_datatable_rows_selected))
})

当某行也被删除时,如何打印它select? (打印值为 TRUE)

据我所知,一个最小的工作示例如下(如果选择 datatable 中的一行,sel() 反应为真):

library(shiny)
library(DT)
ui <- fluidPage(
  DT::dataTableOutput("datatable"),
  textOutput("any_rows_selected")
)
server <- function(input, output) {
  # Output iris dataset
  output$datatable <- DT::renderDataTable(iris, selection = "single")
  # Reactive function to determine if a row is selected
  sel <- reactive({!is.null(input$datatable_rows_selected)})  
  # Output result of reactive function sel
  output$any_rows_selected <- renderText({
    paste("Any rows selected: ", sel())
  })
}
shinyApp(ui, server)

或者,您可以使用 observe(),它将响应对输入 $datatable_rows_selected 的任何命中,包括 NULL。

重新利用 Kristoffer W. B. 的代码:

library(shiny)
library(DT)
ui <- fluidPage(
  DT::dataTableOutput("testtable")
)

server <- function(input, output) {
  # Output iris dataset
  output$testtable<- DT::renderDataTable(iris, selection = "single")


  # Observe function that will run on NULL values
  an_observe_func = observe(suspended=T, {
                    input$testtable_rows_selected
                    isolate({
                      #do stuff here
                      print(input$testtable_rows_selected)
                      })
                    })

  #start the observer, without "suspended=T" the observer 
  #  will start on init instead of when needed
  an_observe_func$resume()

shinyApp(ui, server)

注意几点:

1) 我发现最好以挂起模式启动观察器,这样它不会在程序初始化时启动。您可以在任何需要它的时候打开它...观察...(例如在呈现数据表之后,或者在您想要开始跟踪选择之前)。

2) 使用isolate 来阻止观察者跟踪多个元素。在这种情况下,观察者应该只对输入 $testtable_rows_selected 做出反应,而不是发生其他任何事情。此问题的症状是您的观察者会在一次更改时多次触发。

observeEvent(input$selected,ignoreNULL = FALSE,{...})

ignoreNULL 默认为 TRUE。设置为 FALSE 以在取消选择时观察事件。