我正在尝试在 data.table 中进行一些聚合,但我面临着一个无法找到解决方案的挑战。挑战真的很简单,我想沿着不止一个维度总结 data.table 中的一些值。
我可以毫无问题地运行以下代码:
Export4R[,sum(units),by=Type]
这给出了以下内容:
Type Value
foobar 45
barfoo 25
但现在我想把它分解得更远一点,希望得到这样的表格:
Type Month Value
foobar Mar 12
foobar Apr 7
....
我试着用一行代码来做到这一点,但不幸的是这似乎不起作用:
Export4R[,sum(units),by=Type,Month]
这很可能是一个非常简单的问题,但我很难找到答案。
感谢您的帮助!
最佳答案
Export4R[,sum(units),by="Type,Month"]
或
Export4R[,sum(units),by=list(Type,Month)]
后一种语法允许列名和命名的表达式;例如,
Export4R[,sum(units),by=list(Grp1=substring(Type,1,2), Grp2=Month)]
顺便说一句,您可以格式化多行的长查询:
Export4R[,list(
s = sum(units)
,m = mean(units)
),by=list(
Grp1=substring(Type,1,2)
,Grp2=Month
)]
将逗号放在开头的原因是您可以轻松地添加和注释列,而不会弄乱最后一项的右括号;例如,
Export4R[,list(
s = sum(units)
# ,m = mean(units)
),by=list(
Grp1=substring(Type,1,2)
# ,Grp2=Month
)]
这个想法来自 SQL。
关于r - 如何对 data.table 中的多个列进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13554873/