[R] custom sort?

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


Stavros Macrakis wrote:
> I agree that it is surprising that R doesn't provide a sort function with a
> comparison function as argument. Perhaps that is partly because calling out
> to a function for each comparison is relatively expensive; R prefers vector
> operations.
>
> That said, many useful custom sorts are easy to define by reordering,
> possibly using the 'order' function, e.g.
>
> rr <- function (v) v[order( v %% 10 , v < 500, - v ) ]
> # sort first by last digit (ascending), then by whether < 500, then by
> magnitude (descending)
>
>   

duncan's suggestion ("then define a conversion to numeric") and your
suggestion ("using the 'order' function") can be combined to what could
be considered a form of the schwartzian tranform, e.g.:

    stsort = function(x, transform, ...)
       x[order(transform(x), ...)]

    stsort(1:3, `-`)
    # 3 2 1
    stsort(c('foo', 'f', 'fo'), nchar)
    # "f" "fo" "foo"
    ...

vQ




More information about the R-help mailing list