Search code examples
rmatrixsummary

R - summarize one matrix by another


I have two matrices. The first contains values, and the second contains names corresponding to those values. I would like to sum the values in the first matrix by the corresponding name in the second matrix.

For instance, given the following two example matrices:

set.seed(9)
matrix_names=matrix(sample(paste("name",1:10,sep=""),replace=T),nrow=2,ncol=4); matrix_names
matrix_values=matrix(sample(1:10,8,replace=T),nrow=2,ncol=4); matrix_values

I would like to produce something like:

matrix_names   sum(matrix_values)
  name1                1
  name2                6 
  name3               15  
  name4               15
  name5                5

Any help is appreciated.


Solution

  • un <- unique(as.vector(matrix_names))
    df <- sapply(un, function(x) sum(matrix_values[which(matrix_names == x)]))
    df[order(names(df))]
    name1 name2 name3 name4 name5 
        1     6    15    15     5