Savi
Savi

Reputation: 51

Sort a row of a matrix keeping the col.names along in the resulting matrix in R

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

Answers (1)

bgoldst
bgoldst

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

Related Questions