如何用其他矩阵匹配行和列的值填充矩阵?

时间:2018-01-28 00:06:02

标签: r matrix

我尝试使用其他矩阵与R的值创建一个新矩阵。我尝试在导入值时匹配行和列的名称。这就是尝试做的事情:

我有两个矩阵;

     X1  X2  X3  X4
 X1   0   9   8   0
 X2   1   2   3   5
 X4   6   1   2   4

     X1  X2  X3  X4
 X1  NA  NA  NA  NA   
 X2  NA  NA  NA  NA   
 X3  NA  NA  NA  NA   
 X4  NA  NA  NA  NA   

我想做

     X1  X2  X3  X4
 X1   0   9   8   0   
 X2   1   2   3   5
 X3  NA  NA  NA  NA   
 X4   6   1   2   4

这些矩阵只是我数据集的简单示例,我的实际数据更复杂。

非常感谢,

2 个答案:

答案 0 :(得分:2)

检查两个矩阵中的rownames和colnames匹配将阻止subscript out of bounds错误。见下文。

mat2[rownames(mat2) %in% rownames(mat1), 
     colnames(mat2) %in% colnames(mat1)] <- mat1[rownames(mat1) %in% rownames(mat2), 
                                                 colnames(mat1) %in% colnames(mat2)] 
mat2
#    X1 X2 X3 X4
# X1  0  9  8  0
# X2  1  2  3  5
# X3 NA NA NA NA
# X4  6  1  2  4

数据:

mat1 <- read.table(text = '    X1  X2  X3  X4
 X1   0   9   8   0
                   X2   1   2   3   5
                   X4   6   1   2   4', header = TRUE)

mat1 <- as.matrix(mat1)
mat2 <- matrix(NA, nrow = 4, ncol = 4, dimnames = list(paste0("X", 1:4),
                                                       paste0("X", 1:4)))

答案 1 :(得分:1)

如果我理解你的问题,你可以这样做:

# Building your matrices
mat1 <- matrix(runif(12), nrow = 3, ncol = 4)
mat2 <- matrix(NA, nrow = 4, ncol = 4)
labs <- paste0("x", 1:4)
colnames(mat1) <- colnames(mat2) <- labs
rownames(mat2) <- labs
rownames(mat1) <- labs[c(1:2, 4)]

# 
rows <- sort(unique(c(rownames(mat1), rownames(mat2))))
result <- matrix(NA, nrow = length(rows), ncol = ncol(mat1))
result[match(rownames(mat1), rows), ] <- mat1