Reputation: 51
Suppose I have a matrix with one row X=2 5 7 3 as elements. Implicitly these elements have column names V1-V4. I want to sort these elements, and once sorted they have to also carry their column names along, i.e V1-V4. In this example, once sorted I will need a matrix that has sorted the elements to Y=2 3 5 7 being the second row and 1st row being V1 V4 V2 V3. Thanks.
Upvotes: 0
Views: 899
Reputation: 35324
The column names will naturally move with the column data when you use dimensional indexing:
m <- matrix(c(V1=2,5,7,3),1,4,dimnames=list(NULL,c('V1','V2','V3','V4')));
m;
## V1 V2 V3 V4
## [1,] 2 5 7 3
m <- m[,order(m[1,]),drop=F];
m;
## V1 V4 V2 V3
## [1,] 2 3 5 7
Upvotes: 2