我有一个data.table x
,如下所示:
> data = data.table(a = c(1,2,3,4), x=c(1,1,0,0), y=c(1,1,0,1), id = c(22,22,33,33))
> data
a x y id
1: 1 1 1 22
2: 2 1 1 22
3: 3 0 0 33
4: 4 0 1 33
我希望按id
进行分组,并计算x
和y
为每个id
形成的唯一行数。列a
无关紧要。所以我想要的输出是这样的:
id count
1: 22 1
4: 33 2
我尝试了这个但是我收到了一个错误:
> data[, unique(list(x,y)),by='id']
Error in `[.data.table`(data, , unique(list(x, y)), by = "id") :
j doesn't evaluate to the same number of columns for each group
答案 0 :(得分:4)
您只是缺少length
:
data[, length(unique(list(x,y))), by = 'id']
# id V1
# 1: 22 1
# 2: 33 2
关于评论中的问题,这似乎有效:
data[, length(unique(as.list(.SD))), by = "id", .SDcols = 2:3]
# id V1
# 1: 22 1
# 2: 33 2