Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 对满足所有可能标准的标准的所有值求和_R_Data.table - Fatal编程技术网

R 对满足所有可能标准的标准的所有值求和

R 对满足所有可能标准的标准的所有值求和,r,data.table,R,Data.table,我有一个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

我有一个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
> 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
我尝试了以下方法,在过去取得了一些成功:

> 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
没有钥匙,且钥匙颜色为
时,会收到相同的错误消息。我还尝试了以下操作,将按键设置为
color

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
> 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
我找不到其他好的解决办法。非常感谢您的帮助。

这应该行得通

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
或者如果
包括
包括其他值,则:

a[, list(total=sum(count*(include==1))), keyby = color]
其中,
NA
s可能需要考虑


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

@Ina,那么你只需要一个字符:第一个逗号!啊,你在开玩笑!谢谢你的帮助:)