我有一个 data.table,如下所示:
a <- data.table(color=c("Red","Blue","Red","Green","Red","Blue","Blue"), count=c(1,2,6,4,2,1,1),include=c(1,1,1,1,0,0,1))
> a
color count include
[1,] Red 1 1
[2,] Blue 2 1
[3,] Red 6 1
[4,] Green 4 1
[5,] Red 2 0
[6,] Blue 1 0
[7,] Blue 1 1
我希望创建一个新的 data.table,它只有唯一的颜色值,以及每个匹配 include=1 的计数列的总和,如下所示:
colour total
[1,] Red 7
[2,] Blue 2
[3,] Green 4
我尝试了以下方法,过去我已经取得了一些成功:
> a[,include == 1,list(total=sum(count)),by=colour]
Error in `[.data.table`(a, , include == 1, list(quantity = sum(count)), :
Provide either 'by' or 'keyby' but not both
当a
没有键和键为 时,也会收到同样的错误消息colour
。我也尝试过,将键设置为colour
,以下内容:
> a[,include == 1,list(quantity=sum(count))]
Error in `[.data.table`(a, , include == 1, list(quantity = sum(count))) :
Each item in the 'by' or 'keyby' list must be same length as rows in x (7): 1
我找不到任何其他好的解决方案。非常感谢任何帮助。