<p>Many languages allow you to use a custom comparison function in sorting. R is not an exception, but it is not entirely straightforward – it requires you to define a new class and overload certain operators. Here is how to do it.</p>
<p>Consider the following example. You have a certain number of paired values, for example</p>
<pre>
v &lt;- list(a=c(2,1), b=c(1,3), d=c(1,1), e=c(2,3))
</pre>
<p>The job is to order these pairs in the following way. Given two pairs, p1=(x1, y1) and p2=(x2, y2), p1 &lt; p2 iff one of the following conditions is fulfilled: either x1 &lt; x2 and y1 &lt;= y2, or x1 &lt;= x2 and y1 &lt; y2. The point is that if we draw lines, where one end of the line is at the height x1, and the other end is at the height y1, we want to sort these lines only if they do not cross — at most, only if one of their ends overlaps (but not both, because then the lines would be identical):</p>
<p><img sizes="(max-width: 630px) 100vw, 630px" data-image-description="" data-orig-file="https://logfc.files.wordpress.com/2017/04/example.png" data-orig-size="4133,1633" data-image-title="example" data-comments-opened="1" class="wp-image-472" data-recalc-dims="1" data-attachment-id="472" data-permalink="https://logfc.wordpress.com/2017/04/11/custom-comparison-function-for-sorting-data-in-r/example-2/#main" alt="" data-medium-file="https://logfc.files.wordpress.com/2017/04/example.png?w=300" data-large-file="https://logfc.files.wordpress.com/2017/04/example.png?w=450#038;h=249" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" src="https://logfc.files.wordpress.com/2017/04/example.png?w=450#038;h=249"></p>
<p>On the figure above, left panel, p1 &lt; p2, because one of the ends is below the end of the other line (x1 &lt; x2 and y1=y2). Of course, if y1 &lt; y2 the inequality still holds. On the other hand, the right panel shows a case where we cannot resolve the comparison; the lines cross, so we should treat them as equal.</p>
<p>If now we have a list of such pairs and want to order it, we will have a problem. Here is the thing: the desired order is {d, a, b, e}. The element d=(1,1) is clearly smaller (as defined above) than all the others. However, b=(1,3) is not smaller than a=(2,1), and a is not smaller than b; that means, that a is equal to b, and their order should not be modified.</p>
<p>There is no way to do that with regular tools such as <code>order</code>, especially since x and y may not only be on different scales — they might be even completely different data types! One might be a numeric vector, the other a character string. Or, possibly, a type of requisite from Monty Python (with a defined relation stating that a banana is less than a gun). We must use a custom comparator.</p>
<p>For this, we need to notice that the R functions <code>sort</code> and <code>order</code> rely on the function <code>xtfrm</code>. This in turns relies on the methods <code>==</code>, <code>&amp;gt;</code> and <code>[</code>, defined for a given class. For numeric vectors, for example, these give what you would expect.</p>
<p>Our <code>v</code> vector is a list with elements which are pairs of numbers. For this type of data, there is no comparison defined; and comparing two pairs of numbers results with a vector of two logical numbers, which is not what we want.</p>
<pre>
> v[1] &lt; v[2]
Error in v[1] &lt; v[2] : comparison of these types is not implemented
> v[[1]] &lt; v[[2]]
[1] FALSE  TRUE
</pre>
<p>R, however, is an object oriented language (even if it does not always feel like that). Comparisons (“, <code>==</code>) are generic functions and it is possible to define (or redefine) them for any class of objects. So here is the plan: we invent a new class for the object <code>v</code>, and define custom comparisons for the elements of this class of objects. Remember that if we define a function which name consists of a generic (like &quot;plot&quot; or &quot;[&quot;), a dot, and a name of the class, we are defining the method for the given class:</p>
<pre>
## make v an object of class &quot;foo&quot;
class(v) &lt;- &quot;foo&quot;

## to use the &quot;extract&quot; ([) method, 
## we need to momentarily change the class of x, because 
## otherwise we will end up in an endless loop
'[.foo' &lt;- function(x, i) {
    class(x) &lt;- &quot;list&quot;
    x &lt;- x[i]
    class(x) &lt;- &quot;foo&quot;
    x
}

## define &quot;>&quot; as stated above
## the weird syntax results from the fact that a and b
## are lists with one element, this element being a vector 
## of a pair of numbers
'>.foo' &lt;- function(a,b) {
a &lt;- a[[1]]
b &lt;- b[[1]]
ifelse( (a[1] > b[1] &amp;&amp; a[2] >= b[2])
                     ||
        (a[1] >= b[1] &amp;&amp; a[2] > b[2]), TRUE, FALSE)
}

## if we can't find a difference, then there is no difference
'==.foo' &lt;- function(a, b) 
    ifelse(a > b || b > a, FALSE, TRUE)

## we don't need that, but for the sake of completeness...
'&lt;.foo' &lt;- function(a, b) b > a
</pre>
<p>This will now do exactly what we want:</p>
<pre>
> v[&quot;a&quot;] == v[&quot;b&quot;]
[1] TRUE
> v[&quot;a&quot;] > v[&quot;d&quot;]
[1] TRUE
> sort(v)
$d
[1] 1 1

$a
[1] 2 1

$b
[1] 1 3

$e
[1] 2 3

attr(,&quot;class&quot;)
[1] &quot;foo&quot;
</pre>
<p> <a target="_blank" rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/logfc.wordpress.com/469/"><img alt="" src="http://feeds.wordpress.com/1.0/comments/logfc.wordpress.com/469/" border="0"></a> <img alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" border="0" data-recalc-dims="1"></p>
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/nW_84JfAk8o">