average column values across all rows of a data frame
Asked Answered
S

5

10

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
Siccative answered 20/3, 2011 at 2:35 Comment(0)
P
13

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
Parthenia answered 20/3, 2011 at 2:45 Comment(0)
A
8

Obligatory plyr and reshape solutions:

library(plyr)
ddply(df, "name", function(x) mean(x[-1]))


library(reshape)
cast(melt(df), name ~ ..., mean)
Abjure answered 20/3, 2011 at 3:8 Comment(0)
D
3

And a data.table solution for easy syntax and memory efficiency

library(data.table)
DT <- data.table(df)
DT[,lapply(.SD, mean), by = name]
Dustidustie answered 20/9, 2012 at 4:36 Comment(0)
S
1

I have yet another way. I show it on other example.

If we have matrix xt as:

a b c d
A 1 2 3 4
A 5 6 7 8
A 9 10 11 12
A 13 14 15 16
B 17 18 19 20
B 21 22 23 24
B 25 26 27 28
B 29 30 31 32
C 33 34 35 36
C 37 38 39 40
C 41 42 43 44
C 45 46 47 48

One can compute mean for duplicated columns in few steps:
1. Compute mean using aggregate function
2. Make two modifications: aggregate writes rownames as new (first) column so you have to define it back as a rownames...
3.... and remove this column, by selecting columns 2:number of columns of xa object.

xa=aggregate(xt,by=list(rownames(xt)),FUN=mean)
rownames(xa)=xa[,1]
xa=xa[,2:5]

After that we get:

a b c d
A 7 8 9 10
B 23 24 25 26
C 39 40 41 42

Salmon answered 19/11, 2011 at 22:36 Comment(0)
L
0

You can simply use functions from the tidyverse to group your data by name, and then summarise all remaining columns by a given function (eg. mean):

df <- tibble(name=c("joe","bill","joe","cindy"),
             points=c(1,2,5,10), wins=c(1,3,2,2),
             losses=c(0,0,5,3),
             margin=c(1,4,-2, -2.5))

df %>% dplyr::group_by(name) %>% dplyr::summarise_all(mean)
Lesh answered 23/1, 2020 at 11:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.