更新时间:2022-12-14 15:19:07
使用聚合
:
aggregate(x$Frequency, by=list(Category=x$Category), FUN=sum)
Category x
1 First 30
2 Second 5
3 Third 34
在上面的示例中,多次暗淡可以在列表
中指定。可以通过 cbind
合并同一数据类型的多个聚合指标:
In the example above, multiple dimensions can be specified in the list
. Multiple aggregated metrics of the same data type can be incorporated via cbind
:
aggregate(cbind(x$Frequency, x$Metric2, x$Metric3) ...
(嵌入@thelatemail评论),汇总
也具有公式界面
aggregate(Frequency ~ Category, x, sum)
或如果要聚合多个列,则可以使用。
表示法(也适用于一列)
Or if you want to aggregate multiple columns, you could use the .
notation (works for one column too)
aggregate(. ~ Category, x, sum)
或 tapply
:
tapply(x$Frequency, x$Category, FUN=sum)
First Second Third
30 5 34
使用此数据:
Using this data:
x <- data.frame(Category=factor(c("First", "First", "First", "Second",
"Third", "Third", "Second")),
Frequency=c(10,15,5,2,14,20,3))