dplyr Group By in R: Summarize & Aggregate

In R language, you can use the dplyr package for grouping, summarizing, and aggregating operations. Here is a simple example:

Firstly, install the dplyr package.

install.packages("dplyr")

Next, load the dplyr package.

library(dplyr)

Suppose there is a data frame called df, with columns group and value. It can be grouped by the group column and the values can be summed in the value column.

df <- data.frame(group = c("A", "B", "A", "B"),
                 value = c(10, 20, 30, 40))

df_summary <- df %>%
  group_by(group) %>%
  summarise(total_value = sum(value))
  
print(df_summary)

In the above code, the group_by function is used to group by the group column, the summarise function is used to sum the value column for each group, and a new data frame df_summary is created. Finally, the grouped summary results are printed.

bannerAds