R:在数据表分组,得到我想知道用datatable
,我该如何使用的"special-symbols"
组合得到第一排和其相应的行号每组
问题描述:
第一行和其对应的行号(在参考文献中)为每个group
的数据集?R:在数据表分组,得到我想知道用<code>datatable</code>,我该如何使用的<code>"special-symbols"</code>组合得到<strong>第一排</strong>和<strong>其相应的行号</strong>每组
为例如:
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
得到在MT与基于cyl
每个组的行号:
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
或者'c'而不是'cbind',因为'c(list(1),2)'返回一个将被转换为列的列表。 – thelatemail