Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder columns in a matrix

Tags:

r

Suppose that I have an n row, m column matrix A, and I want to reorder every column in m according to the sorting of some specific row.

For instance, if I take order(A[,k]), that gives me the numeric or alphabetical order of elements in column k. I now want to sort every column in matrix A according to those rankings, so that elements 1...n in every row are ordered to correspond to elements 1...n (by rank) in column k. Is there a simple way to do this without looping over all columns?

like image 976
user1815498 Avatar asked Dec 03 '12 20:12

user1815498


1 Answers

Just use:

A[order(A[,k]),]

For example:

set.seed(21)
A <- matrix(rnorm(50),10,5)
A[order(A[,1]),]
like image 82
Joshua Ulrich Avatar answered Sep 25 '22 21:09

Joshua Ulrich