Re: [R] lexicographic comparison of two vectors

From: Duncan Murdoch <>
Date: Mon, 12 May 2008 15:24:58 -0400

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 mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Mon 12 May 2008 - 19:43:14 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 12 May 2008 - 20:32:11 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive