组ID中的data.table [英] data.table within group id
本文介绍了组ID中的data.table的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有n个分组变量的data.table(在这种情况下为2).我想为每个组添加一个标识符列,如下面所需的输出所示.我尝试了:=
:. N`,我明白为什么它不起作用,但不知道如何实现:
I have a data.table with n grouping variables (in this case 2). I want to add an identifier column for each group as seen in the desired output below. I tried :=
:.N` and I get why that doesn't work but don't know how to make it happen:
library(data.table)
dat <- data.table::data.table(
w = 1:16,
x = LETTERS[1:2],
y = 1:4
)[, w := NULL][order(x, y)]
## x y
## 1: A 1
## 2: A 1
## 3: A 1
## 4: A 1
## 5: A 3
## 6: A 3
## 7: A 3
## 8: A 3
## 9: B 2
## 10: B 2
## 11: B 2
## 12: B 2
## 13: B 4
## 14: B 4
## 15: B 4
## 16: B 4
dat[, z := 1:.N, by = list(x, y)]
dat
所需的输出
## x y z
## 1: A 1 1
## 2: A 1 1
## 3: A 1 1
## 4: A 1 1
## 5: A 3 2
## 6: A 3 2
## 7: A 3 2
## 8: A 3 2
## 9: B 2 3
## 10: B 2 3
## 11: B 2 3
## 12: B 2 3
## 13: B 4 4
## 14: B 4 4
## 15: B 4 4
## 16: B 4 4
推荐答案
dat[, z:=.GRP,by=list(x,y)]
dat
# x y z
# 1: A 1 1
# 2: A 1 1
# 3: A 1 1
# 4: A 1 1
# 5: A 3 2
# 6: A 3 2
# 7: A 3 2
# 8: A 3 2
# 9: B 2 3
# 10: B 2 3
# ...
这篇关于组ID中的data.table的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文