You can use the ungroup() function in dplyr to ungroup rows after using the group_by() function to summarize a variable by group.
The following example shows how to use this function in practice.
Example: How to Use ungroup() in dplyr
Suppose we have the following data frame in R:
#create data frame df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'B'), points=c(14, 18, 22, 26, 36, 34), assists=c(5, 4, 4, 8, 7, 3)) #view data frame df team points assists 1 A 14 5 2 A 18 4 3 A 22 4 4 B 26 8 5 B 36 7 6 B 34 3
Now suppose we use the following code to calculate the mean value of points, grouped by team:
library(dplyr) #calculate mean of points, grouped by team df_new <- df %>% group_by(team) %>% summarize(mean_points = mean(points)) %>% ungroup() #view results df_new # A tibble: 2 x 2 team mean_points 1 A 18 2 B 32
Using this syntax, we’re able to calculate the mean value of points grouped by team, but we’ve lost the assists column.
To retain the assists column, we can use mutate() instead of summarize() and still use ungroup() at the end:
library(dplyr) #calculate mean of points, grouped by team df_new <- df %>% group_by(team) %>% mutate(mean_points = mean(points)) %>% ungroup() #view results df_new # A tibble: 6 x 4 team points assists mean_points 1 A 14 5 18 2 A 18 4 18 3 A 22 4 18 4 B 26 8 32 5 B 36 7 32 6 B 34 3 32
This time we’re able to retain the assists column and by using the mutate() function we’ve simply added a new column called mean_points that shows the mean points value for each team.
Since we used the ungroup() function as well, we can perform calculations on this new data frame without worrying about any calculations being affected by any grouped variables.
If we didn’t use the ungroup() function then the rows of the data frame would still be grouped, which could have unintended consequences when we perform more calculations later on.
The following tutorials explain how to perform other common tasks in R:
How to Filter for Unique Values Using dplyr
How to Filter by Multiple Conditions Using dplyr
How to Count Number of Occurrences in Columns in R