简体   繁体   中英

Order a matrix interms of a vector in R

I have a vector and a matrix . How can I get the following result?

         v = c(1, 3, 2, 4, 7, 5)
         v = sort(v)
         m = matrix(c(1,2, 3, 4,5, 6, 7, 8, 9, 10, 11, 12), ncol=2)
         > res = matrix(c(1, 3, 2, 4, 6, 5, 7, 9, 8, 10, 12, 11), ncol=2)
         > res
              [,1] [,2]
        [1,]    1    7
        [2,]    3    9
        [3,]    2    8
        [4,]    4   10
        [5,]    6   12
        [6,]    5   11

You likely are looking for order instead of sort

m[order(v), ]

     [,1] [,2]
[1,]    1    7
[2,]    3    9
[3,]    2    8
[4,]    4   10
[5,]    6   12
[6,]    5   11

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