[R] sort matrix based on a specific order

Ioannis Kosmidis I.Kosmidis at ucl.ac.uk
Thu Jan 10 22:46:05 CET 2013


mat[match(ind, mat[, 2]), ]
     [,1] [,2]
[1,] "y"  "c" 
[2,] "x"  "b" 
[3,] "z"  "d" 
[4,] "w"  "a" 

though you need to take care if you have cases where ind will contains letters that are not in mat[, 2] and so on (check ?match).

Best,
I

On 10 Jan 2013, at 18:21, array chip <arrayprofile at yahoo.com> wrote:

> 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]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Dr Ioannis Kosmidis
Department of Statistical  Science,
University College,
London, WC1E 6BT, UK
Webpage: http://www.ucl.ac.uk/~ucakiko




More information about the R-help mailing list