2

I have pairs of numbers (x, y), and I would like to order these pairs in such a way, that if x1 <= x2 and y1 <= y2, then (x1, y1) should come before (x2, y2); however, if x1 > x2 and y1 < y2, or the other way around, then the order should not be changed.

Example:

v <- list(a=c(2,1), b=c(1,3), d=c(1,1), e=c(2,3))

Desired ordering: d, a, b, c

In another language, I would call a sort algorithm with a custom comparison function, something like

compare <- function(a, b) {
  if(a[1] < b[1] && a[2] < b[2]) TRUE
  FALSE
}

However, it appears that there is no simple way of doing it in R. Or is there?

Note that sorting by x and then by y will not work.

EDIT 2:

Here is a solution with classes which seems to do precisely what I want.

class(v) <- "foo"
'[.foo' <- function(x, i) { 
     class(x) <- "list"
     structure(x[i], class="foo")
 }
 '>.foo' <- function(a, b) {
      ifelse(
        (a[[1]][1] >= b[[1]][1] & a[[1]][2] > b[[1]][2])
                                ||
        (a[[1]][1] > b[[1]][1] & a[[1]][2] >= b[[1]][2]),
     TRUE, FALSE)
 }
 '==.foo' <- function(a, b) {
    !(a > b || b > a)
 }

Thank you, alexis_laz. Please formulate this as your answer, so I can vote you up.

January
  • 16,320
  • 6
  • 52
  • 74
  • `v[[unlist(lapply(v, FUN=function(r) sum(unlist(lapply(v, FUN=function(a) ifelse(r[1] <= a[1] & r[2] <= a[2], TRUE, FALSE))))))]]` This could do what you might want, but there is a tie in assessing `a` and `b`. Their order is indeterminate given the condition. – nya Apr 10 '17 at 08:42
  • Or maybe: `i<-do.call(rbind,v)` ; `v[order(rowSums(cbind(i[,1]-min(i[,1]),i[,2]-min(i[,2]))))]` – count Apr 10 '17 at 08:49
  • rowSums will not work; the magnitudes (or even types!) of variables on these two positions are likely to differ. For example, if (2,1) is before (1, 195), then the two should not be rearranged. Also, it could be that it is (2, "q") and (1, "a"). I am still figuring out the comment of @nya. – January Apr 10 '17 at 09:34
  • @nya: the indeterminate order is the core of this order. Essentially, what I want is that if the order of a pair cannot be determined, it should be left as it is. – January Apr 10 '17 at 09:37
  • 2
    You could find something helpful [here](http://stackoverflow.com/questions/7515377/sort-a-list-of-nontrivial-elements-in-r) or [here](http://stackoverflow.com/questions/37676537/sorting-list-of-list-of-elements-of-a-custom-class-in-r) – alexis_laz Apr 10 '17 at 10:05
  • Ah, these two questions are really interesting and related. I need to look into that. – January Apr 10 '17 at 12:08
  • @January : What is, exactly, the rationale in your `compare` function? When is "a" larger than/less than/equal to "b"? You'll need to set a class to "v" and define `"["`, `"=="` and, `">"` operators for that class. – alexis_laz Apr 10 '17 at 13:20
  • OK, this seems to work very well. Thank you! – January Apr 10 '17 at 14:53

0 Answers0