How to Calculate Mean (Average) By Group in R

Here are three ways to calculate the mean by the group in R:

  1. Using aggregate()
  2. Using group_by() with summarize() from dplyr package
  3. Using data.table

Method 1: Using aggregate()

The aggregate() function is used to apply a function to each group of a data frame and return the results in a new data frame.

Method 1 - Using aggregate()

df <- data.frame(
  name = c("Krunal", "Ankit", "Rushabh", "Krunal"),
  score = c(85, 90, 78, 95),
  subject = c("Math", "Math", "History", "Sanskrit"),
  grade = c("10th", "11th", "11th", "10th")
)

print(df)
cat("----Calculating the average by name----", "\n")
aggregate(df$score, list(df$name), FUN = mean)

Output

Output of Method 1 - Using aggregate()

Method 2: Using group_by() with summarize()

You can also use the “group_by()” and “summarize()” functions from the dplyr package to calculate the mean of the score group by name.

Method 2 - Using the dplyr package

library("dplyr")

df <- data.frame(
  name = c("Krunal", "Ankit", "Rushabh", "Krunal"),
  score = c(85, 90, 78, 95),
  subject = c("Math", "Math", "History", "Sanskrit"),
  grade = c("10th", "11th", "11th", "10th")
)

print(df)
cat("----Calculating the average by name----", "\n")
df %>% group_by(name) %>% summarise_at(vars(score), list(group = mean))

Output

Output of Method 2 - Using the dplyr package

Method 3: Using data.table()

Method 3 - Using data.table()

library("data.table")

df <- data.frame(
  name = c("Krunal", "Ankit", "Rushabh", "Krunal"),
  score = c(85, 90, 78, 95),
  subject = c("Math", "Math", "History", "Sanskrit"),
  grade = c("10th", "11th", "11th", "10th")
)

print(df)
setDT(df)
cat("----Calculating the average by group using data.table----", "\n")
df[, list(average = mean(score)), by = name]

Output

Output of Method 3 - Using data.table()

That’s it!

Leave a Comment