[R] problem with times

Gavin Simpson gavin.simpson at ucl.ac.uk
Mon Oct 8 19:55:32 CEST 2007


On Mon, 2007-10-08 at 07:38 -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"

Cast them as an object of class "Date" and then this works.

> times <- c("02.07.2007", "03.07.2007","03.09.2007",
"04.07.2007","05.07.2007")
> class(times)
[1] "character"
> as.Date(times, format = "%d.%m.%Y")
[1] "2007-07-02" "2007-07-03" "2007-09-03" "2007-07-04" "2007-07-05"
> sort(as.Date(times, format = "%d.%m.%Y"))
[1] "2007-07-02" "2007-07-03" "2007-07-04" "2007-07-05" "2007-09-03"

If you need to have the dates exactly as you included, then format them

> format(sort(as.Date(times, format = "%d.%m.%Y")), format = "%d.%m.%Y")
[1] "02.07.2007" "03.07.2007" "04.07.2007" "05.07.2007" "03.09.2007"

See ?as.Date (also documents the format method for Date objects)
and ?strftime for the format strings.

G

>  
> Thank you very much in advance,
> Sam
> 
>        
> ---------------------------------
> Pinpoint customers who are looking for what you sell. 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Gavin Simpson                 [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list