[R] Sorting

Hans W Borchers hwborchers at googlemail.com
Sat Feb 6 21:22:10 CET 2010


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.

Would the following function do what you want?

    sortList <- function(L, fun) L[order(sapply(L, fun))]

Here is my test and my understanding of your request;

    L <- list()  # define a list of vectors of varying length
    for (i in 1:10) { n <- sample(1:10, 1); L[[i]] <- runif(n) }

    Ls <- sortList(L, mean)
    sapply(Ls, mean)  # increasing mean values

Hans Werner

> Many thanks for any help!
> 
> Cheers,
> David
> 
>



More information about the R-help mailing list