6

How do you populate an empty matrix with the values of another matrix?

The empty matrix:

> m1 <- matrix(ncol=8, nrow=8)
> rownames(m1) <- c('a','b','c','d','e','f','g','h')
> colnames(m1) <- c('a','b','c','d','e','f','g','h')
> m1
   a  b  c  d  e  f  g  h
a NA NA NA NA NA NA NA NA
b NA NA NA NA NA NA NA NA
c NA NA NA NA NA NA NA NA
d NA NA NA NA NA NA NA NA
e NA NA NA NA NA NA NA NA
f NA NA NA NA NA NA NA NA
g NA NA NA NA NA NA NA NA
h NA NA NA NA NA NA NA NA

The matrix with the values to populate the empty matrix:

> m2 <- matrix(ncol=4, nrow=4)
> rownames(m2) <- c('b','e','h','x')
> colnames(m2) <- c('b','e','h','x')
> m2[,'b'] <- c(1,2,3,1)
> m2[,'e'] <- c(2,1,1,5)
> m2[,'h'] <- c(3,1,3,5)
> m2[,'x'] <- c(1,5,5,1)
> m2
  b e h x
b 1 2 3 1
e 2 1 1 5
h 3 1 3 5
x 1 5 5 1

How do you merge the two matrixes to get this result:

   a  b  c  d  e  f  g  h
a NA NA NA NA NA NA NA NA
b NA  1 NA NA  2 NA NA  3
c NA NA NA NA NA NA NA NA
d NA NA NA NA NA NA NA NA
e NA  2 NA NA  1 NA NA  1
f NA NA NA NA NA NA NA NA
g NA NA NA NA NA NA NA NA
h NA  3 NA NA  1 NA NA  3

Edit: added row/col x in m2, which is not in m1

1 Answer 1

11

Find the column (row) names that both matrices have in common

cols <- colnames(m1)[colnames(m1) %in% colnames(m2)]
rows <- rownames(m1)[rownames(m1) %in% rownames(m2)]

Then assign the appropriate values from m2 to m1

m1[rows, cols] <- m2[rows, cols]
m1
#   a  b  c  d  e  f  g  h
#a NA NA NA NA NA NA NA NA
#b NA  1 NA NA  2 NA NA  3
#c NA NA NA NA NA NA NA NA
#d NA NA NA NA NA NA NA NA
#e NA  2 NA NA  1 NA NA  1
#f NA NA NA NA NA NA NA NA
#g NA NA NA NA NA NA NA NA
#h NA  3 NA NA  1 NA NA  3
Sign up to request clarification or add additional context in comments.

5 Comments

I edited my question. With x in m1, R gives me an "index out of bounds" error.
do you want x to be ignored, or do you want m1 to gain a row and column named x?
ignored, as in my question's result matrix.
Hello - thank you for the useful question and fantatstic answer (upvoted both). I was wondering how you would adapt this to allow for multiple columns/ rows with the same name in m1?
Realise this is a very old question so I have added a new question, specifying this is an extension to this original post. See new chain here stackoverflow.com/questions/66476768/…

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.