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