Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

average column values across all rows of a data frame

I've got a data frame that I read from a file like this:

name, points, wins, losses, margin
joe, 1, 1, 0, 1
bill, 2, 3, 0, 4
joe, 5, 2, 5, -2
cindy, 10, 2, 3, -2.5

etc.

I want to average out the column values across all rows of this data, is there an easy way to do this in R?

For example, I want to get the average column values for all "Joe's", coming out with something like

joe, 3, 1.5, 2.5, -.5
like image 410
Dan Q Avatar asked Mar 20 '11 02:03

Dan Q


1 Answers

After loading your data:

df <- structure(list(name = structure(c(3L, 1L, 3L, 2L), .Label = c("bill", "cindy", "joe"), class = "factor"), points = c(1L, 2L, 5L, 10L), wins = c(1L, 3L, 2L, 2L), losses = c(0L, 0L, 5L, 3L), margin = c(1, 4, -2, -2.5)), .Names = c("name", "points", "wins", "losses", "margin"), class = "data.frame", row.names = c(NA, -4L))

Just use the aggregate function:

> aggregate(. ~ name, data = df, mean)
   name points wins losses margin
1  bill      2  3.0    0.0    4.0
2 cindy     10  2.0    3.0   -2.5
3   joe      3  1.5    2.5   -0.5
like image 102
daroczig Avatar answered Sep 21 '22 01:09

daroczig