Skip to content
Prev 17109 / 398530 Next

formatting date strings

"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
`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
[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:
`data.frame':   2 obs. of  2 variables:
 $ date  : Factor w/ 2 levels "20001001","2001..": 1 2
 $ values: num  10 12


Dirk