Is there a way on R to combine rows to make a total/average?

Viewed 1087

I have a big df which looks like this:

Name      Year    Runs   Average
J. Doe    2016    432    44.5
J. Doe    2017    325    37.4
J. Bloggs 2016    289    54.3

I want to concatenate rows so that I can make a total for each name, rather than split by year. Some columns e.g. Runs would need to be summed and others e.g. Average would need other formulae dependent on other columns. The df is too big to do it manually, so is there a function I can use to combine these rows whenever there is a repeated name?

2 Answers

You can use dplyr:

library(dplyr)
df %>% 
  group_by(Name) %>% 
  summarise(sum_of_runs = sum(Runs),
            average_of_column_x = mean(column_x, na.rm = TRUE))

If you want to sum Runs column and take mean of Average column for each unique value in Name, using data.table you can do :

library(data.table)
setDT(df)[, .(Runs = sum(Runs), Avg = mean(Average)), Name]

#       Name Runs  Avg
#1:    J.Doe  757 41.0
#2: J.Bloggs  289 54.3

Add na.rm = TRUE in sum and mean functions if you have NA values.

data

df <- structure(list(Name = c("J.Doe", "J.Doe", "J.Bloggs"), Year = c(2016L, 
2017L, 2016L), Runs = c(432L, 325L, 289L), Average = c(44.5, 
37.4, 54.3)), class = "data.frame", row.names = c(NA, -3L))
Related