Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在求和之前对R数据进行多次分组_R_Grouping_Aggregate_Summary - Fatal编程技术网

在求和之前对R数据进行多次分组

在求和之前对R数据进行多次分组,r,grouping,aggregate,summary,R,Grouping,Aggregate,Summary,在提供一个汇总表来显示每个组中的值之和之前,我试图通过一些变量对数据进行分组 我创建了以下数据作为示例 Value <- c(21000,10000,50000,60000,2000, 4000, 5500, 10000, 35000, 40000) Group <- c("A", "A", "B", "B", "C", "C", "A", "A", "B", "C") Type <- c(1, 2, 1, 2, 1, 1, 1, 2, 2, 1) Matrix <- c

在提供一个汇总表来显示每个组中的值之和之前,我试图通过一些变量对数据进行分组

我创建了以下数据作为示例

Value <- c(21000,10000,50000,60000,2000, 4000, 5500, 10000, 35000, 40000)
Group <- c("A", "A", "B", "B", "C", "C", "A", "A", "B", "C")
Type <- c(1, 2, 1, 2, 1, 1, 1, 2, 2, 1)
Matrix <- cbind(Value, Group, Type)

Value您可以向
聚合提供多个分组:

df <- data.frame(Value, Group, Type)

> aggregate(df$Value, list(Type = df$Type, Group = df$Group), sum)
  Type Group     x
1    1     A 26500
2    2     A 20000
3    1     B 50000
4    2     B 95000
5    1     C 46000
> aggregate(df$Value, list(Type = df$Type, Group = df$Group), length)
  Type Group x
1    1     A 2
2    2     A 2
3    1     B 1
4    2     B 2
5    1     C 3
dplyr
是另一个选项,@waskuf有一个很好的例子。

使用dplyr(注意,“矩阵”需要是一个data.frame):

库(dplyr)
矩阵%group_按(组、类型)%%>%汇总(总和=总和(值),
Count=n())%>%ungroup()

抱歉,现在应附上Excel示例
>library(data.table)
>dt <- as.data.table(df)
>dt[, .(Count = length(Value), Sum = sum(Value)), 
   by = .(Type, Group)]

   Type Group Count   Sum
1:    1     A     2 26500
2:    2     A     2 20000
3:    1     B     1 50000
4:    2     B     2 95000
5:    1     C     3 46000
library(dplyr)
Matrix <- data.frame(Value, Group, Type)

Matrix %>% group_by(Group, Type) %>% summarise(Sum = sum(Value),
                                               Count = n()) %>% ungroup()