0
表中的行可能會動態更改,但用戶現有的行選擇應保留。選定的行按其行索引存儲,因此當呈現新的datatable()
時,如何保留選定的行?如何在R Shiny應用程序中粘貼DT數據錶行選擇
表中的行可能會動態更改,但用戶現有的行選擇應保留。選定的行按其行索引存儲,因此當呈現新的datatable()
時,如何保留選定的行?如何在R Shiny應用程序中粘貼DT數據錶行選擇
解決方案有兩個部分。首先datatable()
中的selection
參數可以採取表格的列表list(mode='multiple', selected=c(1,3))
第二部分是確定哪些選定的行保留在新表中。 第二部分的一個解決方案是將數據表的副本存儲爲會話變量。當生成新的數據表時,將舊錶與新表進行比較。根據舊錶和新表中的常見行計算一組新的選定行索引。通過使用which(newkeys %in% oldkeys)
習語來找到進入新表格的行索引。
下面是一個例子:
library(shiny)
ui <- fluidPage(
checkboxInput('yellow.only', 'Yellow Only'),
uiOutput('fruit.selection'),
DT::dataTableOutput("dt.fruit.selection")
)
server <- function(input, output) {
fruit.options <- reactive({
all.fruits <- c(grape='Grape', banana='Banana', papaya='Papaya', raspberry='Raspberry')
yellow.fruits <- c(FALSE, TRUE, TRUE, FALSE)
all.fruits[yellow.fruits | !input$yellow.only]
})
fruit.options.df <- reactive({
data.frame(fruits=fruit.options(), some.other.col=nchar(fruit.options()))
})
output$fruit.selection <- renderUI({ selectInput('fruit', 'Fruit', choices=fruit.options(), selected=input$fruit, multiple=TRUE, selectize=FALSE, size=length(fruit.options())) })
output$dt.fruit.selection <- DT::renderDataTable({
if (!exists('fruit.options.cache') || identical(fruit.options.cache, fruit.options.df())) {
rows.selected <- isolate(input$dt.fruit.selection_rows_selected)
} else {
rows.selected <- which(fruit.options.df()$fruit %in% fruit.options.cache$fruits[isolate(input$dt.fruit.selection_rows_selected)])
}
fruit.options.cache <<- fruit.options.df()
DT::datatable(fruit.options.cache, rownames=FALSE, selection=list(mode="multiple", selected=rows.selected))
})
}
# Run the application
shinyApp(ui = ui, server = server)
這也可以從RStudio與shiny::runGist("https://gist.github.com/dkulp2/7ebb1c936d08f3434127e58d7798af28")