简体   繁体   中英

How to replace values from a matrix with another matrix based on column/row names?

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM