R语言 使用Dplyr的Group by函数
Group_by()函数属于R编程语言中的dplyr包,它对数据帧进行分组。Group_by()函数本身不会产生任何输出。它应该与summaryise()函数一起执行一个适当的动作。它的工作原理类似于SQL中的GROUP BY和EXCEL中的透视表。
语法
group_by(col,…)
语法
group_by(col,..) %>% summarise(action)
使用中的数据集 。
Sample_Superstore
单一列上的group_by()
这是最简单的分组方法,只需在group_by()函数中传递要分组的列的名称,并在summaryise()函数中传递要对该分组列执行的操作。
例子: 通过group_by()对单列进行分组
library(dplyr)
 
df = read.csv("Sample_Superstore.csv")
 
df_grp_region = df %>% group_by(Region)  %>%
                    summarise(total_sales = sum(Sales),
                              total_profits = sum(Profit),
                              .groups = 'drop')
 
View(df_grp_region)
输出
多列的Group_by() 函数
Group_by()函数也可以在两个或多个列上执行,列名需要有正确的顺序。分组将根据group_by函数中的第一个列名进行,然后再根据第二个列名进行分组。
例子: 对多列进行分组
library(dplyr)
 
df = read.csv("Sample_Superstore.csv")
 
df_grp_reg_cat = df %>% group_by(Region, Category) %>%
                   summarise(total_Sales = sum(Sales),
                             total_Profit = sum(Profit),
                             .groups = 'drop')
 
View(df_grp_reg_cat)
输出
我们还可以通过替换summary或aggregation函数中的sum来计算平均值、计数、最小值或最大值。例如,我们将找到上面同一个group_by例子的平均销售额和利润。
例子
library(dplyr)
 
df = read.csv("Sample_Superstore.csv")
 
df_grp_reg_cat = df %>% group_by(Region, Category) %>%
                   summarise(mean_Sales = mean(Sales),
                             mean_Profit = mean(Profit),
                             .groups = 'drop')
 
View(df_grp_reg_cat)
输出
极客教程