如何在闪亮的数据表中保存排序? [英] How to save sorting in dataTable in shiny?
问题描述
我在页面上有表格,可以按列进行排序,在我使用反应表重新加载数据后,不会再次排序,这里是 server.R 代码:
I have table on page with possible sorting in columns, by after I reload data with reactive table isn't sorted again, here the server.R code:
library(shiny)
shinyServer(function(input, output) {
# Return the requested dataset
datasetInput <- reactive({
switch(input$dataset2,
"[,...]" = diamonds,
"[10:30,...]" = diamonds,
"[31:50,...]" = diamonds)
})
#"[,...]" = diamonds[,],
#"[10:30,...]" = diamonds[10:30,],
#"[31:50,...]" = diamonds[31:50,])
# Show the first "n" observations
output$view <- renderTable({
head(datasetInput())
})
# a large table, reative to input$show_vars
output$mytable1 <- renderDataTable({
library(ggplot2)
datasetInput()[, input$show_vars, drop = FALSE]
})
})
推荐答案
保留排序顺序(和选择)的最佳方法是使用 proxyDataTable 和 replaceData 来更新你的数据,而不是每次更新数据时都创建一个新表:
The best way to retain sort order (and selection) is to use proxyDataTable and replaceData to update your data, rather than creating a new table each time the data is updated:
mydata = reactive({
df$ID <<- c(df$ID[n], df$ID[-n])
df
})
output$foo = DT::renderDataTable(isolate(mydata()))
proxy = dataTableProxy('foo')
observe({
replaceData(proxy, mydata(), resetPaging = FALSE)
})
不过有几件事需要注意.如果您正在使用模块,请查看此线程以确保将正确的会话变量传递给代理:https://github.com/rstudio/DT/issues/359
There are a couple things to be aware of though. If you are using modules, check out this thread to make sure you are passing the right session variable to the proxy: https://github.com/rstudio/DT/issues/359
此外,如果您对数据表使用 rownames=false,则还必须将参数传递给 replaceData.
Also, if you use rownames=false for your datatable, you must also pass the parameter to replaceData.
如果 proxyDataTable 不是一个选项,你也可以在 DT::renderDataTable 中使用回调:
If proxyDataTable is not an option, you can also use callbacks in DT::renderDataTable:
#include some javascript
tags$head(tags$script(src="my.js"))
#options to renderDataTable
preDrawCallback = JS("initTableOrder"),
drawCallback = JS("saveTableOrder")
my.js 中的 javascript 函数(存储在您的 www 目录中):
The javascript functions in my.js (stored in your www directory):
var tableSortOrderSave;
function initTableOrder(settings, json) {
if(tableSortOrderSave === undefined){
$(this.api().table().order());
}else{
$(this.api().table().order(tableSortOrderSave));
}
}
function saveTableOrder(settings, json) {
order = $(this.api().table().order());
if(order.length > 0){
tableSortOrderSave = order;
}
}
这篇关于如何在闪亮的数据表中保存排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!