繁体   English   中英

如何在R Shiny应用程序中使DT数据表行选择置为粘性

[英]How to make a DT datatable row selection sticky in an R Shiny app

表中的行可以动态更改,但应保留用户现有的行选择。 选定的行按行索引存储,因此当呈现新的datatable() ,如何保留选定的行?

解决方案分为两部分。 首先, datatable()selection参数可以采用列表形式的list(mode='multiple', selected=c(1,3))

第二部分是确定新表中保留哪些选定的行。 第二部分的一种解决方案是将数据表的副本存储为会话变量。 生成新的数据表时,会将旧表与新表进行比较。 根据旧表和新表中的公共行来计算一组新的选定行索引。 通过使用which(newkeys %in% oldkeys)惯用语找到新表中的行索引。

这是一个例子:

library(shiny)

ui <- fluidPage(
  checkboxInput('yellow.only', 'Yellow Only'),
  uiOutput('fruit.selection'),
  DT::dataTableOutput("dt.fruit.selection")
)

server <- function(input, output) {

  fruit.options <- reactive({
    all.fruits <- c(grape='Grape', banana='Banana', papaya='Papaya', raspberry='Raspberry')
    yellow.fruits <- c(FALSE, TRUE, TRUE, FALSE)
    all.fruits[yellow.fruits | !input$yellow.only]
  })

  fruit.options.df <- reactive({
    data.frame(fruits=fruit.options(), some.other.col=nchar(fruit.options()))
  })

  output$fruit.selection <- renderUI({ selectInput('fruit', 'Fruit', choices=fruit.options(), selected=input$fruit, multiple=TRUE, selectize=FALSE, size=length(fruit.options())) })

  output$dt.fruit.selection <- DT::renderDataTable({
    if (!exists('fruit.options.cache') || identical(fruit.options.cache, fruit.options.df())) {
        rows.selected <- isolate(input$dt.fruit.selection_rows_selected)
    } else {
      rows.selected <- which(fruit.options.df()$fruit %in% fruit.options.cache$fruits[isolate(input$dt.fruit.selection_rows_selected)])
    }

    fruit.options.cache <<- fruit.options.df()
    DT::datatable(fruit.options.cache, rownames=FALSE, selection=list(mode="multiple", selected=rows.selected))
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

也可以从RStudio运行带有shiny::runGist("https://gist.github.com/dkulp2/7ebb1c936d08f3434127e58d7798af28")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM