[R] Sorting

Hans W Borchers hwborchers at googlemail.com
Sun Feb 7 00:30:37 CET 2010

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) {
    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

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)))

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

More information about the R-help mailing list