3

我有一个 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

我找不到任何其他好的解决方案。非常感谢任何帮助。

4

1 回答 1

3

这应该工作

library(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[include == 1, list(total=sum(count)), keyby = color]

   color total
1:  Blue     3
2: Green     4
3:   Red     7

从马修编辑:

或者如果include采用(仅)值0然后1

a[, list(total=sum(count*include)), keyby = color]

或者如果include包含其他值,则:

a[, list(total=sum(count*(include==1))), keyby = color]

其中NAs 可能需要考虑。

通过避免矢量扫描,这些可能会更有效i,但这在很大程度上取决于数据大小和属性。这些只需要与最大组一样大的工作内存,而include==1ini需要至少分配一个与nrow(a).

于 2012-08-13T14:05:46.447 回答