2017-09-19 82 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()