Replace an order matrix to a value matrix

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Replace an order matrix to a value matrix

WuyiL
This post has NOT been accepted by the mailing list yet.
All,

I have an ordered matrix like this,
   1  3  2
   3  2  1
   2  3  1

and I have vector V=(98, 0.5, 5)

and i want to get a matrix like this,
0.5 98 5
98  5 0.5
5  98 0.5

I tried to use replace statement but it seems not the good one. Any helps will be appreciated.

WuyiL
Reply | Threaded
Open this post in threaded view
|

Re: Replace an order matrix to a value matrix

arun kirshna
This post has NOT been accepted by the mailing list yet.
This post was updated on .
Hi,
Try this:
mat1<- as.matrix(read.table(text="
   1  3  2
   3  2  1
   2  3  1
",sep="",header=FALSE))
 V<-c(98,0.5,5)
 res<-sapply(seq_len(nrow(mat1)),function(i) V[order(V)][match(mat1[i,],order(V[order(V)]))])
 res
#     [,1] [,2] [,3]
#[1,]  0.5   98  5.0
#[2,] 98.0    5  0.5
#[3,]  5.0   98  0.5

#You could also use:
V1<- as.matrix(V[order(V)])
 sapply(seq_len(nrow(mat1)),function(i) V1[cbind(mat1[,i],1)])
#     [,1] [,2] [,3]
#[1,]  0.5   98  5.0
#[2,] 98.0    5  0.5
#[3,]  5.0   98  0.5
A.K.
Reply | Threaded
Open this post in threaded view
|

Re: Replace an order matrix to a value matrix

WuyiL
This post has NOT been accepted by the mailing list yet.
Thanks for your quick reply. It works perfectly.

WuyiL