Search code examples
rmatrixrowfillcol

add row and column to matrix based on sequence and fill it with NaN


I have a matrix mat_1 with specular rows and columns but one of both is missing. So let's say I want rows and columns following the alphabetical order: a, b, c, d, e, but my matrix is missing one of the letter, i.e. b.

How can I generate a code snippet that finds the gap(s) in the alphabetical sequence in mat_1, adds the missing row and column, and fills the observations with NaN in a second matrix mat_2?

Here is my reproducible example:

set.seed(100)

#create matrix with missing column and row
mat_1 = matrix(rnorm(16), nrow=4, ncol=4, byrow = TRUE) 

#rename columns and rows
dimnames(mat_1) = list(c("a", "c", "d", "e"), c("a", "c", "d", "e")) 

#expected output
> mat_2
           a    b          c           d           e
a -0.5021924  NaN  0.1315312 -0.07891709  0.88678481
b        NaN  NaN        NaN         NaN         NaN
c  0.1169713  NaN  0.3186301 -0.58179068  0.71453271
d -0.8252594  NaN -0.3598621  0.08988614  0.09627446
e -0.2016340  NaN  0.7398405  0.12337950 -0.02931671

Solution

  • There was an answer a minute ago, which I believe was a very good one, and I actually came by again to comment on it with some modifications, and up-vote it, but it seems it was deleted

    In any case here is the updated version of the mentioned answer

    #create matrix with missing column and row
    mat_1 = matrix(rnorm(16), nrow=4, ncol=4, byrow = TRUE) 
    
    #rename columns and rows
    dimnames(mat_1) = list(c("a", "c", "d", "e"), c("a", "c", "d", "e")) 
    
    mat_2 <- matrix(
      NA,
      nrow = length(letters[1:5]),
      ncol = length(letters[1:5]),
      dimnames = list(letters[1:5], letters[1:5]))
    
    mat_2[rownames(mat_1), colnames(mat_1)] <- mat_1
    
    mat_2
    
    #            a  b          c           d           e
    # a -0.5021924 NA  0.1315312 -0.07891709  0.88678481
    # b         NA NA         NA          NA          NA
    # c  0.1169713 NA  0.3186301 -0.58179068  0.71453271
    # d -0.8252594 NA -0.3598621  0.08988614  0.09627446
    # e -0.2016340 NA  0.7398405  0.12337950 -0.02931671