Search code examples
rmatrixdplyr

How to sum values of a matrix according to colnames and rownames?


I have the following matrix:

     Aa   AA
aa    1    0
Aa    31   1
AA    7    3590

how to say in R that I want to sum values within the matrix which do not correspond in terms of column names and row names, in this case: 1 (Aa versus aa), 7 (Aa versus AA), 0 (AA versus aa), 1 (AA versus Aa), so as to get 9?


Solution

  • You could use outer to compare the rownames and column names, leaving a logical matrix of the same dimensions as the original. This can be used to subset the original matrix, which is then summed. That means the following one-liner should do the trick:

    sum(m[!outer(rownames(m), colnames(m), `==`)])
    #> [1] 9
    

    Data used:

    m <- structure(c(1, 31, 7, 0, 1, 3590), dim = 3:2, dimnames = list(
      c("aa", "Aa", "AA"), c("Aa", "AA")))
    
    m
    #>    Aa   AA
    #> aa  1    0
    #> Aa 31    1
    #> AA  7 3590