Add a new column with the desired category, and use that in aggregate
. Here is an example:
d <- data.frame(x=1:12)
rownames(d) <- paste0('X', rep(1:4, 3), '.', rep(1:3, 4))
d
## x
## X1.1 1
## X2.2 2
## X3.3 3
## X4.1 4
## X1.2 5
## X2.3 6
## X3.1 7
## X4.2 8
## X1.3 9
## X2.1 10
## X3.2 11
## X4.3 12
This looks something like your data. Now add the categories as a new column. If you split each name on .
, you want the second entry returned:
d$category <- sapply(strsplit(rownames(d), '[.]'), '[', i=2)
d
## x category
## X1.1 1 1
## X2.2 2 2
## X3.3 3 3
## X4.1 4 1
## X1.2 5 2
## X2.3 6 3
## X3.1 7 1
## X4.2 8 2
## X1.3 9 3
## X2.1 10 1
## X3.2 11 2
## X4.3 12 3
And aggregate based on this new column. .
here means "all other columns" so you will get means of everything other than the new column:
aggregate(.~category, data=d, FUN=mean)
## category x
## 1 1 5.5
## 2 2 6.5
## 3 3 7.5