[R] reverse lexicographic order

Duncan Murdoch dmurdoch at pair.com
Sun Dec 14 23:31:52 CET 2003


On Mon, 15 Dec 2003 10:08:31 +1300, you wrote:

>Hi all,
>
>I have some email addresses that I would like to sort in reverse 
>lexicographic order so that addresses from the same domain will be 
>grouped together. How might that be done?

I'm not sure this is what you want, but this function sorts a
character vector by last letters, then 2nd last, 3rd last, and so on:


revsort <- function(x,...) {
	x[order(unlist(lapply(strsplit(x,''),
		function(x) paste(rev(x),collapse=''))),...)]
}

> revsort(as.character(1:20))
 [1] "10" "20" "1"  "11" "2"  "12" "3"  "13" "4"  "14" "5"  "15" "6"
"16" "7" 
[16] "17" "8"  "18" "9"  "19"

The ... args are given to order(), so na.last=FALSE and
decreasing=TRUE are possibilities.

Duncan Murdoch




More information about the R-help mailing list