[Rd] sort changes datatype of operand

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Aug 18 10:03:35 CEST 2006


On Fri, 18 Aug 2006, Henrik Bengtsson wrote:

Commenting on a much earlier posting than mine!

> On 8/18/06, Prof Brian Ripley <ripley at stats.ox.ac.uk> wrote:

[...]

> > On Thu, 17 Aug 2006, Brahm, David wrote:
> >
> > > On 8/3/2006 10:34 AM, <stephen.ponzio at citigroup.com> noted that,
> > > starting with R-2.3.0, sort() fails to preserve date classes:
> > >
> > > > dates <- seq(Sys.Date(), len=5, by="1 day")
> > > > dates[order(dates)]
> > > > [1] "2006-08-03" "2006-08-04" "2006-08-05" "2006-08-06" "2006-08-07"
> > > > sort(dates)
> > > > [1] 13363 13364 13365 13366 13367
> > >
> > > and Duncan Murdoch <murdoch at stats.uwo.ca> replied:
> > >
> > > > The problem is that some classes assume a particular ordering for
> > > > values; sort can mess them up.  If you know that's not the case, you
> > > > can protect the class yourself:
> > > >   cl <- class(dates)
> > > >   sorteddates <- sort(dates)
> > > >   class(sorteddates) <- cl
> 
> Just curious, what is it about the Date class that make it assume a
> "particular ordering" that sort() can mess up?  

sort() is not written with knowledge of all classes including those not 
yet dreamt of.  Duncan said 'some classes'.

> Why is it wrong to have the following?
> 
> sort.default <- base::sort
> sort <- function(...) UseMethod("sort")
> sort.Date <- function(x, ...) { y <- NextMethod("sort", x, ...);
> class(y) <- class(x); y }

For a start, that drops the "tzone" attribute, and the methods do not 
match the generic.  And it dispatches lists to sort.list().  More 
importantly, it might be used on a class inheriting from "Date" which sort 
did mess up (e.g. one which stored labels in Japanese in an attribute).

It is likely that there will be a solution to this in 2.4.0, fortunately 
written by people with a deeper understanding of the issues (and who have 
actually read the documentation).

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list