[R] Sorting

David Neu david at davidneu.com
Sat Feb 6 21:46:31 CET 2010


On Sat, Feb 6, 2010 at 3:22 PM, Hans W Borchers
<hwborchers at googlemail.com> wrote:
> 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
>>
>>
>
> ______________________________________________
> R-help at 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.
>

Hi Hans,

Thanks for your response, but I need the comparison function to have
access to both vectors

Cheers,
David



More information about the R-help mailing list