如何从已过滤数据表(DT)的选定行中获取数据?

tba*_*s45 6 r shiny dt

DT包允许您使用来获取选定行的索引input$tableID_rows_selected。这对于没有过滤数据的表非常有用。但是,如果我们有一个经过过滤的数据集,则由于行索引已关闭,因此无法使用相同的方法。

那么,对于过滤后的数据集,我们如何在数据表的选定行中获取数据?

在下面,我发布了一个基本的闪亮应用程序,其中显示了四个表:第一个是原始mtcars数据集,第二个是在第一个中获取选定的行。第三和第四做相同的事情,但是在“过滤器” sliderInput上过滤了数据集之后。

library(shiny)
library(DT)
library(dplyr)

ui <- fluidPage(
  DT::dataTableOutput("origTable"),
  DT::dataTableOutput("origTableSelected"),
  sliderInput("filter", label = "Filter by cyl", min = 4, max = 8, step = 2, value = 6),
  DT::dataTableOutput("filteredTable"),
  DT::dataTableOutput("filteredTableSelected")
)


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

  output$origTable <- DT::renderDataTable({
    datatable(
      mtcars,
      selection = list(mode = "multiple"),
      caption = "Original Data"
    )
  })

  origTable_selected <- reactive({
    ids <- input$origTable_rows_selected
    mtcars[ids,]
  })

  output$origTableSelected <- DT::renderDataTable({
    datatable(
      origTable_selected(),
      selection = list(mode = "multiple"),
      caption = "Selected Rows from Original Data Table"
    )
  })

  output$filteredTable <- DT::renderDataTable({
    datatable(
      filter(mtcars, cyl == input$filter),
      selection = list(mode = "multiple"),
      caption = "Filtered Table (based on cyl)"
    )
  })

  filteredTable_selected <- reactive({
    ids <- input$filteredTable_rows_selected
    mtcars[ids,]
  })

  output$filteredTableSelected <- DT::renderDataTable({
    datatable(
      filteredTable_selected(),
      selection = list(mode = "none"),
      caption = "Table that gets data from unfiltered original data"
    )
  })
}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

tba*_*s45 7

一种方法:在您的filteredTable_selected()函数中创建要放入第四个DT中的数据的地方,filter(mtcars, cyl == input$filter)就像对第三个表一样使用,而不是mtcars。这样,行索引将匹配。

如果您担心较大的数据集上的性能问题,只需过滤反应式表达式中的数据即可缓存其输出。这样,您过滤的内容不会超过input $ filter值的更改。

server <- function(input, output, session) {
  filteredTable_data <- reactive({
    filter(mtcars, cyl == input$filter)
  })

  output$filteredTable <- DT::renderDataTable({
    datatable(
      filteredTable_data(),
      selection = list(mode = "multiple"),
      caption = "Filtered Table (based on cyl)"
    )
  })

  filteredTable_selected <- reactive({
    ids <- input$filteredTable_rows_selected
    filteredTable_data()[ids,]
  })

  output$filteredTableSelected <- DT::renderDataTable({
    datatable(
      filteredTable_selected(),
      selection = list(mode = "none"),
      caption = "Table that gets data from unfiltered original data"
    )
  })
}
Run Code Online (Sandbox Code Playgroud)