将 DT table 重置为原始排序顺序

Reset a DT table to the original sort order

我有一个闪亮的应用程序,带有允许列排序的 DT table。替换数据后,我还想删除用户可能单击的任何列排序。但是,当数据被替换时,它会根据 table 中指定的排序自动排序。我没有看到任何选项可以将排序重置为 replaceData 函数的一部分或作为独立的代理函数。是否可以在不重新渲染 table?

的情况下执行此操作
library(DT)
library(shiny)

ui <- fluidPage(
    DTOutput(outputId = "table"),
    actionButton(inputId = "replace", label = "Replace Data")
)

server <- function(input, output) {
    
    output$table <- renderDT({
        datatable(data = data.frame(COL_1 = c(1, 3, 2)), rownames = FALSE)
    })
    
    observeEvent(input$replace, {
        
        data <- data.frame(COL_1 = c(4, 6, 5))
        
        replaceData(proxy = dataTableProxy(outputId = "table"),
                    data = data,
                    rownames = FALSE)
        
    })
    
}

shinyApp(ui = ui, server = server)

我想出了一个 javascript 解决方案。

library(DT)
library(shiny)
library(shinyjs)

clearSorting <- function(proxy) {
  runjs(paste0("$('#' + document.getElementById('", proxy$id,"').getElementsByTagName('table')[0].id).dataTable().fnSort([]);"))
}

ui <- fluidPage(
  DTOutput(outputId = "table"),
  actionButton(inputId = "replace", label = "Replace Data"),
  useShinyjs()
)

server <- function(input, output) {
  
  output$table <- renderDT({
    datatable(data = data.frame(COL_1 = c(1, 3, 2)), rownames = FALSE)
  })
  
  observeEvent(input$replace, {
    
    data <- data.frame(COL_1 = c(4, 6, 5))
    
    clearSorting(proxy = dataTableProxy(outputId = "table"))
    
    replaceData(proxy = dataTableProxy(outputId = "table"),
                data = data,
                rownames = FALSE)
    
  })
  
}

shinyApp(ui = ui, server = server)