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

______________________________________________
R-help@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.

Reply via email to