[Rd] order(x,y, decreasing = c(FALSE, TRUE)) - how / elegantly?

From: Martin Maechler <maechler_at_stat.math.ethz.ch>
Date: Thu, 21 Aug 2008 19:41:51 +0200


I've found the need to compute a version of order(x,y) where I want the sort order
for *increasing* x and *decresing* y ...

something we could imagine could be provided in the future as

  order(x,y, decreasing = c(FALSE, TRUE))

i.e., using a 'vectorized' decreasing argument. {No, I'm not volunteering right now!}

I've found the following R-level solution and like to quiz you for more elegant / faster solutions {but I am not really interested in replacing  order(x) by sort.list(x, method="quick") and similar things;  one thing to consider *is* using an 'na.last = . ' correctly,  and I haven't had the need for that and so not bothered to "do it"}

## Here's a script with my version and a small example ## (if you want speed comparisons, use larger examples) :

orderXuYd <- function(x,y)
{

## Purpose: order(x,y): x up, y down
## ----------------------------------------------------------------------
## Arguments: x,y: vectors of the same length
## ----------------------------------------------------------------------
## Author: Martin Maechler, Date: 21 Aug 2008

    ix <- order(x) 
    xx <- x[ix]
    iy <- tapply(y[ix], xx, order, decreasing = TRUE)

## Note: 'SIMPLIFY', 'USE.NAMES', 'use.names' are just for efficiency:
    unlist(mapply(`[`, split(ix,xx), iy,
                  SIMPLIFY = FALSE, USE.NAMES = FALSE),
           use.names = FALSE)

}
x <- c(1, 1, 2, 0, 0, 2, 1, 2, 2, 0, 2)
y <- c(27, 21, 45, 11, 13, 58, 35, 74, 95, 16, 122)
ii <- orderXuYd(x,y)

## yes, this is it :
cbind(ii=ii, x=x[ii],y=y[ii])

Yes, the real reason this goes to R-devel is that it might be neat to provide this (well, its generalization) via an enhanced order() function.

Martin Maechler, ETH Zurich

PS: I will be basically offline all day tomorrow, so don't

    expect my reactions to your ideas quickly



R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Thu 21 Aug 2008 - 17:45:02 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 21 Aug 2008 - 18:37:18 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive