[R] formatting date strings
Dirk Eddelbuettel
edd at debian.org
Wed Feb 13 06:16:47 CET 2002
"Jeremy" == Jeremy Whish <Jeremy.Whish at csiro.au> writes:
Jeremy> I have a simulation model that out puts dates in a standard
Jeremy> dd/mm/yy format R reads this as a factor and I cant find anything
Jeremy> that will allow me to convert them to a date. In S+ I have used a
Jeremy> chron() function that required you to specify the format of the
Jeremy> input date and the format of the output date. My question is: does
Jeremy> R have such a function? If not, can any one suggest a way to tell
Jeremy> R that information in dd/mm/yy format being read in with
Jeremy> read.table() is actually a date.
R has a (ported) cron package which you install, but R also has the (more
powerful) DateTimeClasses. See the help pages for DateTimeClasses, as.POSIXct
and, in particular, strptime.
Here is a small example [ note that I use %Y for yyyy, not %y for yy ]
First a data frame is created
> DF<-data.frame(date=c("10/1/2000","12/2/2001"), values=c(10,12))
> str(DF)
`data.frame': 2 obs. of 2 variables:
$ date : Factor w/ 2 levels "10/1/2000","12/..": 1 2
$ values: num 10 12
and the date information is parsed using strptime() with format information
> strptime(levels(DF[,"date"]),"%m/%d/%Y")
[1] "2000-10-01" "2001-12-02"
which can then be reformatted, among other things. Here the format method of
the DateTimeClasses is used to impose the %Y%m%d format I prefer:
> levels(DF[,"date"]) <- format(strptime(levels(DF[,"date"]),"%m/%d/%Y"), "%Y%m%d")
> str(DF)
`data.frame': 2 obs. of 2 variables:
$ date : Factor w/ 2 levels "20001001","2001..": 1 2
$ values: num 10 12
Dirk
--
Good judgment comes from experience; experience comes from bad judgment.
-- Fred Brooks
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list