简体   繁体   中英

Mapping one matrix to another matrix position

I will do my best to explain this. I have a data set, out of which I create a matix from one column and do a tcrossprod on it, simplified example data set is...

key value
a1  1000
a2  500
a3  1500
a5  200

My problem arises as I have another matrix that I want to scale the original matrix with which I have calculated separately, simplified example would be...

    a1  a2  a3  a4  a5
a1  1   5   10  15  50
a2  5   1   20  25  75
a3  10  20  1   30  80
a4  15  25  30  1   100
a5  50  75  80  100 1

I am looking to map the second matrix to the first but I can't figure out a way to do it, I am looking to end up with two matrices that I can multiply together, eg, the first matrix is the result of the trcrossprod the second matrix is calculated separately.

The two matrix do not have the same dimensions which is why I am looking to map the corresponding values of the second matrix into the same dimensions as the first so I have a simple scalar matrix calculation.

    v1      v2      v3      v4          a1  a2  a3  a4  a5
1,  1000000 500000  1500000 200000      a1  1   5   10  50
2,  500000  250000  750000  100000      a2  5   1   20  75
3,  1500000 750000  2250000 300000      a3  10  20  1   80
4,  200000  100000  300000  40000       a5  50  75  80  1

So the keys of the first matrix need to map to the second in the correct position so I can do a simple scaling of matrix_1 * matrix_2.

I would then get a new matrix that looks like this...

    v1       v2       v3        v4
1,  1000000  2500000  15000000  10000000
2,  2500000  250000   15000000  7500000
3,  15000000 15000000 2250000   24000000
4,  10000000 7500000  24000000  40000
# Reproduce data
df1 <- read.table(header = TRUE, text = "key value
a1  1000
a2  500
a3  1500
a5  200")
v1 <- as.matrix(df1[, 2, drop = FALSE])
rownames(v1) <- df1[[1]]
m1 <- v1 %*% t(v1)

#         a1     a2      a3    a5
# a1 1000000 500000 1500000 2e+05
# a2  500000 250000  750000 1e+05
# a3 1500000 750000 2250000 3e+05
# a5  200000 100000  300000 4e+04

m2 <- as.matrix(read.table(header = TRUE, text = "    a1  a2  a3  a4  a5
a1  1   5   10  15  50
a2  5   1   20  25  75
a3  10  20  1   30  80
a4  15  25  30  1   100
a5  50  75  80  100 1"))


m1 * do.call("[", c(list(m2), dimnames(m1)))

#         a1      a2       a3      a5
# a1 1.0e+06 2.5e+06 15000000 1.0e+07
# a2 2.5e+06 2.5e+05 15000000 7.5e+06
# a3 1.5e+07 1.5e+07  2250000 2.4e+07
# a5 1.0e+07 7.5e+06 24000000 4.0e+04

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