在求和之前多次对 R 数据进行分组
Grouping R data multiple times before summing
在提供摘要 table 显示每个组内值的总和之前,我尝试按多个变量对我的数据进行分组。
我创建了以下数据作为示例。
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)
我想先通过 'Group' 变量对上述数据进行分组,然后通过 'Type' 变量对值进行求和并获得类似于我处理的附加示例的输出 Excel。如果我只想按一个变量分组,我通常会使用聚合函数,但不确定是否可以将其转换为多个变量?
除此之外,我还需要提供一个相同的 table,但值是使用 "count" 函数而不是 "sum".
计算的
非常感谢!
您可以向 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 有很好的例子。
使用dplyr(注意"Matrix"需要是data.frame):
library(dplyr)
Matrix <- data.frame(Value, Group, Type)
Matrix %>% group_by(Group, Type) %>% summarise(Sum = sum(Value),
Count = n()) %>% ungroup()
我创建了以下数据作为示例。
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)
我想先通过 'Group' 变量对上述数据进行分组,然后通过 'Type' 变量对值进行求和并获得类似于我处理的附加示例的输出 Excel。如果我只想按一个变量分组,我通常会使用聚合函数,但不确定是否可以将其转换为多个变量?
除此之外,我还需要提供一个相同的 table,但值是使用 "count" 函数而不是 "sum".
计算的非常感谢!
您可以向 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 有很好的例子。
使用dplyr(注意"Matrix"需要是data.frame):
library(dplyr)
Matrix <- data.frame(Value, Group, Type)
Matrix %>% group_by(Group, Type) %>% summarise(Sum = sum(Value),
Count = n()) %>% ungroup()