[R] lexicographic comparison of two vectors

Duncan Murdoch murdoch at stats.uwo.ca
Mon May 12 21:24:58 CEST 2008


On 5/12/2008 2:58 PM, Gabriel Valiente wrote:
> Is there any built-in way to lexicographically compare two vectors of  
> the same length in R? The textbook algorithm could be coded as follows:
> 
> lex.cmp <- function (vec1,vec2) {
>    for (j in 1:length(vec1)) {
>      if (vec1[j] < vec2[j]) { return(-1) }
>      if (vec1[j] > vec2[j]) { return(1) }
>    }
>    return(0)
> }


I don't think there's any standard function for this.  You could write 
one as above, or slightly faster as

lex.cmp <- function(vec1, vec2) {
   index <- which.min(vec1 == vec2)  # find the first diff
   sign(vec1[index] - vec2[index])   # assumes numeric
}

If you don't want to assume numeric data, you may need to expand that 
last line to a series of comparisons like yours, but with index in place 
of j, e.g.

   if (vec1[index] < vec2[index]) { return(-1) }
   if (vec1[index] > vec2[index]) { return(1) }
   return(0)

(unless there's a compare function in some package or other.)

Duncan Murdoch



More information about the R-help mailing list