R:通过在数据表中分组,得到每组的第一行及其对应的行号

R: by grouping in datatable, get the first row and their corresponding row numbers for each group

我想知道如何使用 datatable,如何使用 "special-symbols" 的组合来获得 第一行 它们对应的行每个 group?

的数据集中的行号 (在参考中)

例如:

Library(data.table)  
copy(mtcars) -> mt
setDT(mt) -> mt

获取 cyl 每组的第一行:

 mt[, .SD[1], by = cyl]

    cyl  mpg disp  hp drat   wt  qsec vs am gear carb
1:   6 21.0  160 110 3.90 2.62 16.46  0  1    4    4
2:   4 22.8  108  93 3.85 2.32 18.61  1  1    4    1
3:   8 18.7  360 175 3.15 3.44 17.02  0  0    3    2

根据cyl:

得到每组对应的mt中的行号
mt[, .I[1], by = cyl]
   cyl V1
1:   6  1
2:   4  3
3:   8  5

预期输出:

    cyl  mpg disp  hp drat   wt  qsec vs am gear carb   row_N
1:   6 21.0  160 110 3.90 2.62 16.46  0  1    4    4    1
2:   4 22.8  108  93 3.85 2.32 18.61  1  1    4    1    3
3:   8 18.7  360 175 3.15 3.44 17.02  0  0    3    2    5

我尝试了以下但没有成功:

mt[, .SD[1], by= cyl][mt[, .I[1], by=cyl]]
mt[, .SD[1], by= cyl][mt[, `:=` (row_N = .I[1], by=cyl)]]

非常感谢任何解释方面的帮助。

一种方法是将列与 cbind 组合在一起。

mt[, cbind(.SD[1], row_N=.I[1]), by = cyl]
   cyl  mpg disp  hp drat   wt  qsec vs am gear carb row_N
1:   6 21.0  160 110 3.90 2.62 16.46  0  1    4    4     1
2:   4 22.8  108  93 3.85 2.32 18.61  1  1    4    1     3
3:   8 18.7  360 175 3.15 3.44 17.02  0  0    3    2     5