[R] sort time
Marc Schwartz
marc_schwartz at comcast.net
Mon Oct 8 17:33:36 CEST 2007
On Mon, 2007-10-08 at 07:26 -0700, Samuel Okoye wrote:
> Hello, I have got the following problem:
> > times <- c("02.07.2007", "03.07.2007","03.09.2007", "04.07.2007","05.07.2007")
> > mode(times)
> [1] "numeric"
> > tim <- as.character(times)
> > mode(tim)
> [1] "character"
> > sort(times)
> [1] "02.07.2007" "03.07.2007" "03.09.2007" "04.07.2007" "05.07.2007"
>
> Is it possible to get
> > function(sort(times))
> [1] "02.07.2007" "03.07.2007" "04.07.2007" "05.07.2007" "03.09.2007"
>
> Thank you very much in advance,
> Sam
You need to convert 'times' to a Date class object, which can be sorted
as dates and then re-formatted for output:
> format(sort(as.Date(times, format = "%d.%m.%Y")), "%d.%m.%Y")
[1] "02.07.2007" "03.07.2007" "04.07.2007" "05.07.2007" "03.09.2007"
Otherwise, you are sorting based upon a character vector, the order of
which will be locale dependent. Locale issues are likely why your
'times' object is initially a numeric vector and not a character
vector.
You can of course encapsulate the above in a function.
See ?as.Date
HTH,
Marc Schwartz
More information about the R-help
mailing list