*46*

Often you may want to calculate the mean by group in R. There are three methods you can use to do so:

**Method 1: Use base R.**

aggregate(df$col_to_aggregate, list(df$col_to_group_by), FUN=mean)

**Method 2: Use the dplyr() package.**

**library(dplyr)
df %>%
group_by(col_to_group_by) %>%
summarise_at(vars(col_to_aggregate), list(name = mean))
**

**Method 3: Use the data.table package.**

**library(data.table)
dt[ ,list(mean=mean(col_to_aggregate)), by=col_to_group_by]
**

The following examples show how to use each of these methods in practice.

**Method 1: Calculate Mean by Group Using Base R**

The following code shows how to use the **aggregate() **function from base R to calculate the mean points scored by team in the following data frame:

#create data frame df #view data frame df team pts rebs 1 a 5 8 2 a 8 8 3 b 14 9 4 b 18 3 5 b 5 8 6 c 7 7 7 c 7 4 #find mean points scored by team aggregate(df$pts, list(df$team), FUN=mean) Group.1 x 1 a 6.50000 2 b 12.33333 3 c 7.00000

**Method 2: Calculate Mean by Group Using dplyr**

The following code shows how to use the **group_by****()** and **summarise_at()** functions from theÂ **dplyr** package to calculate the mean points scored by team in the following data frame:

library(dplyr)#create data frame df #find mean points scored by teamdf %>% group_by(team) %>% summarise_at(vars(pts), list(name = mean)) # A tibble: 3 x 2 team name1 a 6.5 2 b 12.3 3 c 7

**Method 3: Calculate Mean by Group Using data.table**

The following code shows how to calculate the mean points scored by team in the following data frame:

library(data.table)#create data frame df #convert data frame to data table setDT(df) #find mean points scored by teamdf[ ,list(mean=mean(pts)), by=team] team mean 1: a 6.50000 2: b 12.33333 3: c 7.00000

Notice that all three methods return identical results.

**Related:** A Complete Guide to the mean Function in R

**Additional Resources**

How to Calculate the Sum by Group in R

How to Calculate Quantiles by Group in R