[R] custom sort?

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Fri May 29 09:26:32 CEST 2009


Duncan Murdoch wrote:
> On 28/05/2009 6:06 PM, Steve Jaffe wrote:
>> hmm, that is what I was afraid of. I considered that but thought to
>> myself,
>> surely there must be an easier way.  I wonder why this feature isn't
>> available. It's there in scripting languages, like perl, but also in
>> "hardcore" languages like C++ where std::sort and sorted containers
>> allow
>> the user to provide a comparison function (even for builtin types
>> like int).
>> It's hard to believe that you have to jump through more hoops to do a
>> custom
>> sort in R than in C++ ...
>>
>>
>> You put a class on the vector...
>>
>
> Each of the things I described to you would take about a line of code,
> plus the logic of the comparisons.  So the hoops R makes you jump
> through amount to 2-4 extra lines of code.  C++  is probably going to
> take at least that much.

it's not just about the amount of code.  defining a comparator is
conceptually different from defining a class to sort, e.g., regular
numbers or strings.  passing an additional comparator argument to a
sorting routine is more convenient and readable than wrapping an object
into a dummy class for the mere purpose of sorting it. 

"You put a class on the vector (e.g. using class(x) <- "myvector"), then
define a conversion to numeric (e.g. xtfrm.myvector) or actual
comparison methods (you'll need ==.myvector, >.myvector, and
is.na.myvector). "

    x = 3:1
    class(x) = 'foo'

    '==.foo' = function(...) FALSE
    '>.foo' = function(...) FALSE
    sort(x)
    # 1 2 3  

    '==.foo' = function(...) TRUE
    '>.foo' = function(...) TRUE
    sort(x)
    # 1 2 3  

    '==.foo' = function(...) TRUE
    '>.foo' = function(...) FALSE
    sort(x)
    # 1 2 3  

    '==.foo' = function(...) FALSE
    '>.foo' = function(...) TRUE
    sort(x)
    # 1 2 3  

hmm, doesn't seem to work.  it also won't do for the case when lists
('generic vectors') are to be sorted:

    x = structure(list(1,2,3), class='foo')
    sort(x)
    # Error in switch(ties.method, average = , min = , max =
.Internal(rank(x[!nas],  :
    #   unimplemented type 'list' in 'greater'

  
vQ




More information about the R-help mailing list