R 对满足所有可能标准的标准的所有值求和
我有一个data.table,如下所示: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
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,那么你只需要一个字符:第一个逗号!啊,你在开玩笑!谢谢你的帮助:)