2016-07-21 126 views
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) 

回答

3

一種方法:在你的filteredTable_selected()函數,在那裏你創建你把你的第四DT的數據,使用filter(mtcars, cyl == input$filter)像你這樣爲你的第三個表,而不是mtcars。這樣,行索引就會匹配。

如果您擔心大型數據集上的性能問題,只需將數據過濾爲反應式表達式即可緩存其輸出。這樣,您不會過濾超過您的輸入$過濾器值更改。

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" 
    ) 
    }) 
} 
+0

我在寫一個問題,然後想出來。想想我會張貼它,讓別人知道。 https://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ – tbadams45

+0

@whilethereislight是的,當然,這是非常高興你分享你的發現與我們,謝謝 – Learner