Message-ID: <E66794E69CFDE04D9A70842786030B931B8EFDCB@PA-MBX04.na.tibco.com>
Date: 2013-01-10T18:30:20Z
From: William Dunlap
Subject: sort matrix based on a specific order
In-Reply-To: <1357842101.979.YahooMailNeo@web122903.mail.ne1.yahoo.com>
You can use factor() or match() to specify a particular order. E.g.,
> mat<-cbind(c('w','x','y','z'),c('a','b','c','d'))
> ind<-c('c','b','d','a')
> mat[ order(match(mat[,2], ind)), ]
[,1] [,2]
[1,] "y" "c"
[2,] "x" "b"
[3,] "z" "d"
[4,] "w" "a"
> mat[ order( factor(mat[,2], levels=ind) ), ]
[,1] [,2]
[1,] "y" "c"
[2,] "x" "b"
[3,] "z" "d"
[4,] "w" "a"
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of array chip
> Sent: Thursday, January 10, 2013 10:22 AM
> To: r-help at r-project.org
> Subject: [R] sort matrix based on a specific order
>
> Hi I have a character matrix with 2 columns A and B, If I want to sort the matrix based on
> the column B, but based on a specific order of characters:
>
> mat<-cbind(c('w','x','y','z'),c('a','b','c','d'))
> ind<-c('c','b','d','a')
>
> I want "mat" to be sorted by the sequence in "ind":
>
> ???? [,1] [,2]
> [1,] "y"? "c"
> [2,] "x"? "b"
> [3,] "z"? "d"
> [4,] "w"? "a"
>
> Is there any simple function that can do this?
>
> Thanks
>
> John
>
> [[alternative HTML version deleted]]