[Rd] sort changes datatype of operand (PR#9121)
Duncan Murdoch
murdoch at stats.uwo.ca
Thu Aug 3 17:32:35 CEST 2006
On 8/3/2006 10:34 AM, stephen.ponzio at citigroup.com wrote:
> Full_Name: Stephen Ponzio
> Version: 2.3.1
> OS: Windows
> Submission from: (NULL) (199.67.138.42)
>
>
> Given a vector of dates, sort returns a vector of numerics instead of dates.
> This is different from the behavior in version 2.2, where dates were returned.
> In this respect, sort is not equivalent to order.
>
>> 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
>
>> class(dates[order(dates)])
> [1] "Date"
>> class(sort(dates))
> [1] "numeric"
This is not a bug, it's documented behaviour in ?sort:
>
> As from R 2.3.0, all attributes are removed from the return value
> except names, which are sorted. (If 'partial' is specified even
> the names are removed.) Note that this means that the returned
> value has no class, except for factors and ordered factors (which
> are treated specially and whose result is transformed back to the
> original class).
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
You could put this into your own sort.Date function, but it won't be
called automatically: sort is not a generic.
sort.Date <- function(x) {
cl <- class(x)
structure(sort(x), class=cl)
}
Duncan Murdoch
More information about the R-devel
mailing list