Home > OS >  Comparing matrices in R using row and column names
Comparing matrices in R using row and column names

Time:03-30

I am trying to compare two 5x5 matrices based on row and column names. Note that in matrix b the names for row 2 and row 4 have been swapped.

a <- matrix(1:25, nrow = 5)
colnames(a) = c("col1", "col2", "col3", "col4", "col5")
rownames(a) = c("row1", "row2", "row3", "row4", "row5")
a

b <- matrix(1:25, nrow = 5)
colnames(b) = c("col1", "col2", "col3", "col4", "col5")
rownames(b) = c("row1", "row4", "row3", "row2", "row5")
b

c <- b-a
c

     col1 col2 col3 col4 col5
row1    0    0    0    0    0
row4    0    0    0    0    0
row3    0    0    0    0    0
row2    0    0    0    0    0
row5    0    0    0    0    0

When calculating the difference c = b - a, the code returns a matrix of zeros as if it was looking for the position of the elements in the matrix rather that the row and column index. I'd expect the result for row 4 to be:

d <- a["row4",] - b["row4",]
col1 col2 col3 col4 col5 
   2    2    2    2    2

Any idea how to do this?

CodePudding user response:

a - b[sort(rownames(b)),]

     col1 col2 col3 col4 col5
row1    0    0    0    0    0
row2   -2   -2   -2   -2   -2
row3    0    0    0    0    0
row4    2    2    2    2    2
row5    0    0    0    0    0

If the column names are in different order as well, you could add a sort(colnames(b)) after the comma.

BTW, I advice not to use c as a name for an object in R, since c is a built-in function to create a vector.

CodePudding user response:

The following example will subtract b from a, using the common rows and columns.

ro <- intersect(rownames(a), rownames(b))
co <- intersect(colnames(a), colnames(b))

a[ro,co] - b[ro,co]

##>      col1 col2 col3 col4 col5
##> row1    0    0    0    0    0
##> row2   -2   -2   -2   -2   -2
##> row3    0    0    0    0    0
##> row4    2    2    2    2    2
##> row5    0    0    0    0    0

  • Related