# [R] Sorting

David Neu david at davidneu.com
Sun Feb 7 02:12:41 CET 2010

```On Sat, Feb 6, 2010 at 6:30 PM, Hans W Borchers
> David Neu <david <at> davidneu.com> writes:
>
>> David Neu <david <at> davidneu.com> writes:
>>
>> Hi,
>>
>> I have a list of vectors (of varying lengths).  I'd like to sort this
>> list by applying a function to each pair of vectors in the list and
>> returning information to sorting routine that let's it know which one
>> is larger.
>>
>> To solve problems like this in Common Lisp, the sort function accepts
>> a function as an argument.  The arguments to this function are two
>> elements of the list which is being sorted.  The writer of the
>> function returns t (TRUE in R) when the first argument to the function
>> is larger than the second and nil (FALSE in R) otherwise.
>>
>> I'm wondering if there is some way to accomplish this in R.
>
> I don't know whether there is a way to do it with the 'base::sort' function
> -- and I too would very much like to know for an application of my own --,
> but you can always define your own sorting, like here a simple bubble sort:
>
>    bubbleSort.list <- function(L, comp) {
>    stopifnot(is.list(L))
>    n <- length(L)
>    if (n <= 1) return(L)
>    for (i in 1:n) {
>        for (j in 2:n) {
>        b <- L[[j]]
>        if (comp(L[[j]], L[[j-1]])) {
>            L[[j]] <- L[[j-1]]
>            L[[j-1]] <- b
>        }
>        }
>    }
>    return(L)
>    }
>
> If your comparing function, for example, compares first length and then mean:
>
>    comp <- function(L1, L2) {
>      if (length(L1)<length(L2) ||
>         (length(L1)==length(L2) && mean(L1)<mean(L2)))
>        return(TRUE)
>      else
>        return(FALSE)
>    }
>
> then the following test example will turn out to be correct:
>
>    L <- list()
>    for (i in 1:100) L[[i]] <- runif(sample(1:20, 1))
>
>    Ls <- bubbleSort.list(L, comp)
>    is.unsorted(sapply(Ls, length))  # incl. mean for equal length
>
> If bubblesort is too slow, implement your own heapsort or quicksort.
>
>> Many thanks for any help!
>>
>> Cheers,
>> David
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

Hi Hans,

Great minds think alike! :)  I also decided to write my own sorting
routine.  I happened to pick insertion sort.

I do think would be a  very nice feature to have in R.  I've it useful
in other languages e.g.
http://www.lispworks.com/documentation/lw50/CLHS/Body/f_sort_.htm
http://wiki.python.org/moin/HowTo/Sorting

Thanks for all of your help and for the confirmation that this is the way to go!

Cheers,
David

```