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)
set.seed(2009)
rr(sample(1000,30))
[1] 840 670 580 140 100 10 991 901 881 561 231 71 722 662 432 222 32
473 53
[20] 24 645 796 86 697 607 567 397 257 77 818 568 428 198 619 569 479 439
299
Hope this helps,
-s
On Thu, May 28, 2009 at 6:06 PM, Steve Jaffe <[email protected]> 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...
>
> --
> View this message in context:
> http://www.nabble.com/custom-sort--tp23770565p23770964.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> [email protected] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.