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.