1
DT包允许您使用input$tableID_rows_selected
获取选定行的索引。这对于没有过滤数据的表格非常有用。但是,如果我们有一个过滤的数据集,我们不能使用相同的方法,因为行索引已关闭。如何从筛选的数据表(DT)的选定行中获取数据?
对于过滤的数据集,那么我们如何获得数据表的选定行中的数据?
下面我发布了一个基本的闪亮应用程序,它显示了四个表格:第一个是原始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)
我在写一个问题,然后想出来。想想我会张贴它,让别人知道。 https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ – tbadams45
@whilethereislight是的,当然,这是非常高兴你分享你的发现与我们,谢谢 – Learner