如何在Shiny DT数据表中预选行

How to pre-select rows in Shiny DT datatables

本文关键字:数据表 DT Shiny      更新时间:2023-09-26

我在这个Shiny数据表中使用Shiny(0.12.0)和DT(0.0.65)进行行选择。我想预选前5行。我试过了:

  • 在datatable中使用callback JS改变行的类。然而,这并没有反映在input$x1_rows_selected变量中。只有背景/高亮会因为CSS而改变。
  • 在选项列表中的rowCallbackcallback中使用.click()。这在加载页面时也不起作用。但是,当我通过控制台/浏览器开发工具运行相同的代码时,它可以工作(更新input$x1_rows_selected)。

callback JS:

output$x1 = DT::renderDataTable({
    datatable(cars,
        rows = $("#x1 tbody tr");
        $(rows).slice(0,5).each(function() {
            $(this).click();
        });
    )
})

此功能已添加到DT(>= 0.1.3)。例子:

library(shiny)
if (packageVersion('DT') < '0.1.3') devtools::install_github('rstudio/DT')
library(DT)
shinyApp(
  ui = fluidPage(
    fluidRow(
      h1('Client-side processing'),
      DT::dataTableOutput('x1'),
      h1('Server-side processing'),
      DT::dataTableOutput('x2')
    )
  ),
  server = function(input, output, session) {
    output$x1 = DT::renderDataTable(
      iris, server = FALSE,
      selection = list(mode = 'multiple', selected = c(1, 3, 8, 12))
    )
    output$x2 = DT::renderDataTable(
      iris, server = TRUE,
      selection = list(mode = 'multiple', selected = rownames(iris)[c(1, 3, 8, 12)])
    )
  }
)

如果你想绑定一个响应到选定的输入,这里有一个快速的例子来说明如何完成。

我已经修改了上面的客户端示例,以添加一个selectInput,允许您动态选择要突出显示的行。将此扩展到多选择场景将是微不足道的。

library(shiny)
if (packageVersion('DT') < '0.1.3') devtools::install_github('rstudio/DT')
library(DT)
shinyApp(
  ui = fluidPage(
    fluidRow(
      shiny::selectInput("myrow", "Select Row", choices = seq(nrow(iris))),
      h1('Client-side processing'),
      DT::dataTableOutput('x1'),
      h1('Server-side processing'),
      DT::dataTableOutput('x2')
    )
  ),
  server = function(input, output, session) {
    myselected <- shiny::reactive(as.integer(input$myrow))
    output$x1 = DT::renderDataTable(
      iris, server = FALSE,
      selection = list(mode = 'multiple', selected = myselected())
    )
    output$x2 = DT::renderDataTable(
      iris, server = TRUE,
      selection = list(mode = 'multiple', selected = rownames(iris)[c(1, 3, 8, 12)])
    )
  }
)