根据序列将行和列添加到矩阵并用 NaN 填充

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

我有一个矩阵 mat_1,其中有镜面反射行和列,但两者之一都丢失了。假设我想要按字母顺序排列的行和列:a、b、c、d、e,但我的矩阵缺少一个字母,即 b.

如何生成一个代码片段,找到 mat_1 中字母顺序中的空白,添加缺失的行和列,并在一秒钟内用 NaN 填充观察结果矩阵 mat_2?

这是我的可重现示例:

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

一分钟前有一个回答,我认为是一个很好的答案,我实际上又来评论了一些修改,并投票给它,但它似乎被删除了

无论如何,这里是上述答案的更新版本

#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