【发布时间】:2016-11-25 11:42:45
【问题描述】:
DT 包允许您使用input$tableID_rows_selected 获取选定行的索引。这对于没有过滤数据的表非常有用。但是,如果我们有一个过滤数据集,我们就不能使用同样的方法,因为行索引是关闭的。
那么,对于过滤后的数据集,我们如何获取数据表的选定行中的数据?
下面,我发布了一个基本的闪亮应用程序,它显示了四个表:第一个是原始 mtcars 数据集,第二个获取第一个中的选定行。第三个和第四个做同样的事情,但是在“过滤器”滑块输入上过滤数据集之后。
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)
【问题讨论】: