Shiny DT: Freeze rownames while sorting?

冷暖自知 提交于 2019-12-07 09:21:07

问题


I'm designing a Shiny app to rank people based on a variety of metics. Using the DT sorting feature, I want users to be able to click on any column and sort by it.

It seems natural to use the rownames as the rank; the problem is that these numbers sort along with the rest of the table. Is there any way to freeze this column so the rank numbers stay the same while the rest of the table sorts? Perhaps with a JavaScript function?

EDIT: In the example below, when I click "Metric_1," I want the rownames to stay 1, 2, 3, 4, instead of sorting to 3, 2, 1, 4 to match the new order of Person C, Person B, Person A, Person D. END EDIT

I don't see this option on the RStudio help page: https://rstudio.github.io/DT/

# Simplified example

library(shiny)
library(DT)


ui <- fluidPage(

    DT::dataTableOutput("table")

)

server <- function(input, output) {

    output$table <- DT::renderDataTable({

        x <- data.frame(
            Name = c("Person A", "Person B", "Person C", "Person D"), 
            Metric_1 = c(8, 7, 4, 10), 
            Metric_2 = c(3, 5, 2, 8)
        )

        datatable(x)

    })
}

shinyApp(ui = ui, server = server)

回答1:


Here's a working example using this SO answer

library(shiny)
library(DT)


ui <- fluidPage(

  DT::dataTableOutput("table")

)

server <- function(input, output) {
  js <- c(
    "table.on('draw.dt', function(){",
    "  var PageInfo = table.page.info();",
    "  table.column(0, {page: 'current'}).nodes().each(function(cell,i){", 
    "    cell.innerHTML = i + 1 + PageInfo.start;",
    "  });",
    "})")

  output$table <- DT::renderDataTable({

    x <- data.frame(
      Name = c("Person A", "Person B", "Person C", "Person D"), 
      Metric_1 = c(8, 7, 4, 10), 
      Metric_2 = c(3, 5, 2, 8)
    )

    datatable(x, callback = JS(js))

  })
}

shinyApp(ui = ui, server = server)


来源:https://stackoverflow.com/questions/57060061/shiny-dt-freeze-rownames-while-sorting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!