数据表总和和子集 [英] 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))
我想按年份和组对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
这篇关于数据表总和和子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!