简体   繁体   中英

For values in a matrix get value out of a vector and replace the matrix values

Ok complicated title, but actually it's quite easy to explain :-)

I have a Matrix M:

M<-matrix(c(1,3,4,5,7,6,2, 2,5,1,3,4,7,6, 1,7,3,2,5,4,6),nrow=3,ncol=7, byrow=TRUE)
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    3    4    5    NA    6    2
[2,]    2    5    1    3    4    7    6
[3,]    1    7    3    2    5    4    NA

And I have a vector with weights W:

W<-c(0.4,0.2,0.15,0.1,0.07,0.05,0.02)

Now I want to replace all values in the matrix depending on the number in the matrix, with the value in the vector at this respective position. So my resulting Matrix (it needs to be a matrix) should look like this:

[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]  0.4  0.15 0.1   0.07  NA  0.05  0.2
[2,]  0.2  0.07 0.4   0.15  0.1   0.02  0.05
[3,]  0.4  0.02 0.15  0.2   0.07  0.1   NA

But I don't know how to achieve this.

M2<-W[M]

didn't achieve the desired results..any advice?

matrix(W[M], nrow=nrow(M))

     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]  0.4 0.15 0.10 0.07   NA 0.05 0.20
[2,]  0.2 0.07 0.40 0.15 0.10 0.02 0.05
[3,]  0.4 0.02 0.15 0.20 0.07 0.10   NA

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