Automatic row numbers (after filtering DT in shiny)

拟墨画扇 提交于 2019-12-25 03:47:16

问题


I would like to get the rownames count start again from 1,2,3... after filtering the datatable. Is it possible?

Here is simple code:

library(shiny)
library(DT)
library(ggplot2)

x <- as.numeric(1:1000)
y <- as.numeric(1:1000)
data <- data.frame(x,y)

shinyApp(
  ui = fluidPage(dataTableOutput('tbl'),
                 plotOutput('plot1')),
  server = function(input, output) {
    output$tbl = renderDataTable({
      datatable(data, filter = "top", rownames=TRUE,options = list(
        pageLength = 300, lengthMenu = c(100,200,300,400,500,600)
      ))
    })
    output$plot1 = renderPlot({
      filtered_data <- input$tbl_rows_all
      ggplot(data = data[filtered_data, ], aes(x = x,y = y)) + geom_line()
    })
  }
)

So as an example if i filter column x to get the values from 50-..., I would like the rownames to start not (in this case) as 50,51.., but as 1,2...

Thanks for any help!


回答1:


The Datatables docs had an example of how do to this here. You can use the javascript code and your datatable callback argument:

   output$tbl = renderDataTable({
                        datatable(data, filter = "top", rownames=TRUE,options = list(
                                pageLength = 300, lengthMenu = c(100,200,300,400,500,600)
                        ),
                        callback=JS("table.on( 'order.dt search.dt', function () {
                                table.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
                                      cell.innerHTML = i+1;});}).draw();"))
                })

This only changes the values of the HTML displayed, the actual rownames of the dataset are not changed.



来源:https://stackoverflow.com/questions/35502931/automatic-row-numbers-after-filtering-dt-in-shiny

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