2

I would like to merge two matrices based on row and column names. Here is an example:

mat1 <- matrix(c(0,0,1,0,1,0,1,1,0), nrow=3, byrow=TRUE)
colnames(mat1) <- c("A", "B", "C")
rownames(mat1) <- c("x", "y", "z")
mat1

  A B C
x 0 0 1
y 0 1 0
z 1 1 0

mat2 <- matrix(0, nrow=4, ncol = 6)
colnames(mat2) <- c("A", "B", "C", "D", "E", "F")
rownames(mat2) <- c("w", "x", "y", "z")
mat2

  A B C D E F
w 0 0 0 0 0 0
x 0 0 0 0 0 0
y 0 0 0 0 0 0
z 0 0 0 0 0 0

How can I efficiently write the values of mat1 into mat2? I would like to obtain:

  A B C D E F
w 0 0 0 0 0 0
x 0 0 1 0 0 0
y 0 1 0 0 0 0
z 1 1 0 0 0 0

I have tried for loops but that seems tedious and inefficient. Ideas?

1 Answer 1

3

If the 'mat2' is a super set of 'mat1', then use the row/column indexing to subset the 'mat2' and assign the 'mat1'

mat2[row.names(mat1), colnames(mat1)] <- mat1
mat2
#   A B C D E F
# w 0 0 0 0 0 0
# x 0 0 1 0 0 0
# y 0 1 0 0 0 0
# z 1 1 0 0 0 0
4
  • 1
    @SFront Thank you;. Can I know your expectations
    – akrun
    Commented Apr 15, 2019 at 15:32
  • And how do you do it if it is not the super set? Is it mat2[which(row.names(mat1) == row.names(mat2)), which(colnames(mat1) == colnames(mat2))] <- mat1[which(row.names(mat1) == row.names(mat2)), which(colnames(mat1) == colnames(mat2))] ?
    – S Front
    Commented Apr 16, 2019 at 0:01
  • 1
    @SFront I meant is i1 <- match(row.names(mat2), row.names(mat1), nomatch = 0);i2 <- match(row.names(mat1), row.names(mat2), nomatch = 0);j1 <- match(colnames(mat2), colnames(mat1), nomatch = 0);j2 <- match(colnames(mat1), colnames(mat2), nomatch = 0);mat2[i2, j2] <- mat1[i1, j1]
    – akrun
    Commented Apr 16, 2019 at 5:35
  • 1
    @SFront I guess I answered the example you posted
    – akrun
    Commented Apr 16, 2019 at 5:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.