按多个列组合并合计其他多个列 [英] Group by multiple columns and sum other multiple columns
本文介绍了按多个列组合并合计其他多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个大约200列的数据框架,其中我想将表格分成前10个左右,这是因素和总和其余的列。
I have a data frame with about 200 columns, out of them I want to group the table by first 10 or so which are factors and sum the rest of the columns.
我有列出了我想要分组的所有列名称以及我想要聚合的所有列的列表。
I have list of all the column names which I want to group by and the list of all the cols which I want to aggregate.
输出格式
是否有使用软件包的解决方案 data.table
, plyr
或任何其他?
Is there a solution using packages data.table
, plyr
or any other?
推荐答案
data.table 方式是:
DT[, lapply(.SD,sum), by=list(col1,col2,col3,...)]
或
DT[, lapply(.SD,sum), by=colnames(DT)[1:10]]
其中 .SD
是(D)ata 排除组列的(S)ubset。 (Aside:如果您需要一般性地引用组列,则它们在 .BY
。)
where .SD
is the (S)ubset of (D)ata excluding group columns. (Aside: If you need to refer to group columns generically, they are in .BY
.)
这篇关于按多个列组合并合计其他多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文