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 ______________________________________________ R-help@r-project.org 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.