[R] Sorting
    David Winsemius 
    dwinsemius at comcast.net
       
    Sat Feb  6 20:30:15 CET 2010
    
    
  
On Feb 6, 2010, at 1:21 PM, David Neu wrote:
> 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.
>
Here's one way, although there may be options within the netherworld  
of S4 methods that I am not smart enough to navigate:
GT <- function(x,y) x > y
x <- c(8,7,4,2,5,7,5,8,4,5,8,3,0)
 > sum(GT(x[1],x))
[1] 10  # so the first element is greater than 10 other elements
x[order(rowSums(sapply(x, GT, y=x)) )]
  # compare the number of other elements one by one and sort by the  
direction of your choice
# [1] 8 8 8 7 7 5 5 5 4 4 3 2 0
#There's probably a method around the "reversal" of the usual sort  
order:
 > x[order(rowSums(sapply(x, GT, y=x)) ,decreasing=TRUE)]
  [1] 0 2 3 4 4 5 5 5 7 7 8 8 8
Perhaps use instead negation of the logical matrix that the sapply  
creates:
 > x[order(rowSums(!sapply(x, GT, y=x)) )]
  [1] 0 2 3 4 4 5 5 5 7 7 8 8 8
 > sortFn <- function(x, FUN=">", ...) x[order(rowSums(!sapply(x, GT,  
y=x)) , ...)]
 > sortFn(x, GT)
  [1] 0 2 3 4 4 5 5 5 7 7 8 8 8
 > sortFn(x, GT, decreasing=TRUE)
  [1] 8 8 8 7 7 5 5 5 4 4 3 2 0
-- 
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
    
    
More information about the R-help
mailing list