data.table 总和和子集 [英] data.table sum and subset
问题描述
我有一个要汇总的 data.table
I have a data.table that I am wanting to aggregate
library(data.table)
dt1 <- data.table(year=c("2001","2001","2001","2002","2002","2002","2002"),
group=c("a","a","b","a","a","b","b"),
amt=c(20,40,20,35,30,28,19))
我想按年份和分组sum
amt,然后过滤任何给定组的总和 amt 大于 100.
I am wanting to sum
the amt by year and group and then filter where the summed amt for any given group is greater than 100.
我已经确定了 data.table 的总和.
I've got the data.table sum nailed.
dt1[, sum(amt),by=list(year,group)]
year group V1
1: 2001 a 60
2: 2001 b 20
3: 2002 a 65
4: 2002 b 47
我的最终过滤级别有问题.
I am having trouble with my final level of filtering.
我正在寻找的最终结果是:
The end outcome I am looking for is:
year group V1
1: 2001 a 60
2: 2002 a 65
作为 a) 60 + 65 >100
而 b) 20 + 47 <= 100
任何关于如何实现这一点的想法都会很棒.
Any thoughts on how to achieve this would be great.
我查看了这个 数据.table 按组求和并返回具有最大值的行 并且想知道它们是否是解决我的问题的同样雄辩的解决方案.
I had a look at this data.table sum by group and return row with max value and was wondering whether or not their is an equally eloquent solution to my problem.
推荐答案
data.table
中的单行:
dt1[, lapply(.SD,sum), by=.(year,group)][, if (sum(amt) > 100) .SD, by=group]
# group year amt
#1: a 2001 60
#2: a 2002 65
这篇关于data.table 总和和子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!