Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pad missing data in a matrix with NA based on another matrix

I have two adjacency matrices where the second one has some missing data (that means these two matrices are of different square size) but how do I pad the missing data with NA in the second matrix?

Data below:

#first matrix
t1 = matrix(
  c(1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1),
  nrow = 4,  
  ncol = 4,        
  byrow = TRUE         
)
rownames(t1) <- c("a","b", "c", "d")
colnames(t1) <- c("a","b", "c", "d")

#second matrix
t2 = matrix(
  c(1, 1, 0, 0, 0, 1, 0, 0, 1),
  nrow = 3,  
  ncol = 3,        
  byrow = TRUE         
)
rownames(t2) <- c("a","c", "d") #assume data from b are missing here
colnames(t2) <- c("a","c", "d")

Expected outcome for the second matrix:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  a  b  c  d
a 1  NA 1  0
b NA NA NA NA
c 0  NA 0  1
d 0  NA 0  1

I have a much larger dataset and so a more efficient approach will be appreciated@

>Solution :

If row and column names can be relied upon:

t3 <- t1
t3[] <- NA
t3[rownames(t2), colnames(t2)] <- t2

t3
#    a  b  c  d
# a  1 NA  1  0
# b NA NA NA NA
# c  0 NA  0  1
# d  0 NA  0  1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading