R Aggregating Data
aggregate() summarises one column of a data frame group by group. A formula names the column to summarise and the column that forms the groups.
Average a column group by group
The formula asks for the score column summarised by the group column. Each group gets one row holding its mean score.
df <- data.frame(group = c("a", "a", "b", "b"), score = c(10, 20, 30, 50))
print(aggregate(score ~ group, data = df, mean))Change the summary function
The last argument can be any summary function. sum totals each group, and length counts the rows in each group.
df <- data.frame(group = c("a", "a", "b", "b"), score = c(10, 20, 30, 50))
print(aggregate(score ~ group, data = df, sum))
print(aggregate(score ~ group, data = df, length))Group with a list instead of a formula
The by form takes the values first and a list of the groups second. Its result columns are named Group.1 and x.
df <- data.frame(group = c("a", "a", "b", "b"), score = c(10, 20, 30, 50))
print(aggregate(df$score, by = list(df$group), mean))Example
survey <- data.frame(team = c("red", "red", "blue", "blue", "blue"), rating = c(4, 5, 3, 5, 4))
print(aggregate(rating ~ team, data = survey, mean))Key points
- aggregate() returns a new data frame with one row per group.
- The formula score ~ group reads as score summarised by group.
- The data argument names the frame the columns come from.
- The last argument names the summary function, such as mean, sum or length.
- The formula form keeps the original column names in the result.
- The by form takes the values and a list of groups in place of a formula.
- The by form names its result columns Group.1 and x.
In this example the rating column is averaged for each team. The result holds one row per team, with the teams in alphabetical order.
Note
The rows of the result come back in group order.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
In aggregate(score ~ group, data = df, mean), what does the formula ask for?