如何使用基于列/行名称的另一个矩阵替换矩阵中的值?

时间:2023-02-10 04:18:07

I have a small matrix:

我有一个小矩阵:

SMALL<-matrix(c(1:9),3, 3)
colnames(SMALL)<-c("25","36","48")
rownames(SMALL)<-c("18","25","48")

looks like:

   25 36 48
18  1  4  7
25  2  5  8
48  3  6  9

And a large matrix:

还有一个大矩阵:

LARGE<-matrix(0,4, 4)
colnames(LARGE)<-c("12","25","36","48")
rownames(LARGE)<-c("18","25","38","48")

looks like:

   12 25 36 48
18  0  0  0  0
25  0  0  0  0
38  0  0  0  0
48  0  0  0  0

I would like to replace values from the large matrix by those from the small one based on the column/row names.

我想用大型矩阵中的值替换基于列/行名称的小矩阵中的值。

Looking for this result:

寻找这个结果:

   12 25 36 48
18  0  1  4  7
25  0  2  5  8
38  0  0  0  0
48  0  3  6  9

Any ideas ?

有任何想法吗 ?

1 个解决方案

#1


5  

Assuming there is a match for each col and row name of SMALL in LARGE:

假设LALL中的每个col和行名称匹配为:

i <- match(rownames(SMALL), rownames(LARGE))
j <- match(colnames(SMALL), colnames(LARGE))

LARGE[i,j] <- SMALL
#   12 25 36 48
#18  0  1  4  7
#25  0  2  5  8
#38  0  0  0  0
#48  0  3  6  9

#1


5  

Assuming there is a match for each col and row name of SMALL in LARGE:

假设LALL中的每个col和行名称匹配为:

i <- match(rownames(SMALL), rownames(LARGE))
j <- match(colnames(SMALL), colnames(LARGE))

LARGE[i,j] <- SMALL
#   12 25 36 48
#18  0  1  4  7
#25  0  2  5  8
#38  0  0  0  0
#48  0  3  6  9