2017-09-19 30 views
1

Excel Example我想在提供显示每个组内的值总和的摘要表之前,按照多个变量对数据进行分组。在求和之前多次对R数据进行分组

我已经创建了以下数据为例。

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) 

欲组以上的数据首先由“组”的变量,并且然后由“类型”变量然后求和值,并得到类似的附接例如我Excel的工作的输出。如果我只想用一个变量进行分组,我通常会使用聚合函数,但我不确定是否可以将其转换为多个变量?

除此之外,我还需要提供一个相同的表格,但值是用“count”函数而不是“sum”来计算的。

非常感谢提前!

+0

道歉,Excel的例子,现在应该附 –

回答

1

您可以提供多个分组到aggregate

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 

有可能是更容易使用,如data.table其他包:

>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 

dplyr是另一种选择和@waskuf具有很好的例子那个。

1

使用dplyr(注意, “黑客帝国” 必须是一个data.frame):

library(dplyr) 
Matrix <- data.frame(Value, Group, Type) 

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