汇总多列 [英] Sum multiple columns
本文介绍了汇总多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个函数,该函数将根据前两列中的值对数据帧中的列求和,例如我有一个矩阵M,
I am trying to write a function that will sum the column(s) in the data frame according to the values in the first two columns.For example I have a matrix M,
Crs gr P_7 P_8
38 1 3 16
38 1 12 45
38 1 9 28
40 2 3 9
40 2 14 29
40 1 4 3
40 2 8 2
我想先对column1(crs)的列求和,然后对column2(gr)求和。结果将是
I want to sum the columns according to column1(crs) first and then column2(gr). Result will be,
Crs gr P_7 P_8
38 1 24 89
40 2 25 40
40 1 4 3
当前我正在使用,
M <- M[, list(sum(P_7),sum(P_8)), by=list(Crs,gr)]
但是问题是,我必须定义不会固定的列名。因此,我想知道如何在不定义列名称的情况下执行此操作。
提前谢谢!
But the problem with this, is that I have to define the names of columns which wont be fixed. So, I was wondering how can I do this without defining the names of the columns. Thanks in advance!
推荐答案
您正在寻找的内容:
M[, lapply(.SD, sum), by = list(Crs, gr)]
这篇关于汇总多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文