如何在 DT 的左边有一个像 Excel 这样的行号?

How to have a row number like in Excel in the left in DT?

我想在左侧有一个始终显示 1, 2, 3, ... 的行号(就像 excel 行号一样),以便用户在单击后有一个参考行号来查看感兴趣的行的排名在列上更改 table.

的顺序

编辑:

library(DT)
n <- 20
set.seed(1)
df <- data.frame(customer_id = sample(10),
           amount_2016 = round(runif(n) * 16),
           amount_2017 = round(runif(n) * 17),
           amount_2018 = round(runif(n) * 18),
           amount_2019 = round(runif(n) * 19))

datatable(df)

点击amount_2016后显示

它显示 17, 14, 1, 2, 15, ... 我希望它保持 1, 2, 3, ... 就像 Excel

诀窍是定义一个 callback JS() 函数来实现动态行号计数器的 table.on behaviour

这是一个最小的可重现 RMarkdown 示例:

---
title: "Untitled"
output: html_document
---

```{r}
library(DT)
datatable(
    iris,
    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;
            } );
    } )"))
```

生产

无论您如何对列进行排序,行号将始终保持为 1、2、3、...