Reputation: 25
I have a big matrix, like this:
m:
0 60 120 180... (column names)
0 2 4 5 9
0 6 8 7 6
0 5 2 6 4
0 3 4 1 3
60 4 5 3 1
60 4 6 10 2
.
.
(row names)
I would like to calculate the mean of the rows, which has the same name. How can i do this in R? The outcome would look like this matrix:
k:
0 60 120 180... (column names)
0 4 4,5 4,75 5,5
60 4 5,5 6,5 1,5
.
.
(row names)
I guess it is really basic, but I just can not figure out. I would appreciate a little help. Thank you!
Upvotes: 0
Views: 1193
Reputation: 887118
Here is one option with aggregate
from base R
aggregate(m, list(row.names(m)), mean)
# Group.1 0 60 120 180
#1 0 4 4.5 4.75 5.5
#2 60 4 5.5 6.50 1.5
Or using tapply
tapply(m, list(row.names(m)[row(m)], colnames(m)[col(m)]), FUN = mean)
Or using by
do.call(rbind, by(m, row.names(m), FUN = colMeans))
# 0 60 120 180
#0 4 4.5 4.75 5.5
#60 4 5.5 6.50 1.5
Or with split
t(sapply(split(as.data.frame(m), row.names(m)), colMeans))
m <- structure(c(2, 6, 5, 3, 4, 4, 4, 8, 2, 4, 5, 6, 5, 7, 6, 1, 3,
10, 9, 6, 4, 3, 1, 2), .Dim = c(6L, 4L), .Dimnames = list(c("0",
"0", "0", "0", "60", "60"), c("0", "60", "120", "180")))
Upvotes: 1