tags:

views:

170

answers:

3

Hi Guys,

Would like to change the date format in R. My data frame is shown below and would like to change all the date formats to "%d/%m/%Y" .Any help would be appreciated!

df:

id    bdate       wdate        ddate
1   09/09/09    12/10/09     2009-09-27

Thanks,

Bazon

+2  A: 
df$ddate<-strftime(df$ddate,"%d/%m/%Y")
df$bdate<-strftime(strptime(df$bdate,"%d/%m/%y"),"%d/%m/%Y")
df$wdate<-strftime(strptime(df$wdate,"%d/%m/%y"),"%d/%m/%Y")
James
For `strptime` (and any other function), you want `=` to assign the argument value, here for `format`, as in `df$bdate<-strftime(strptime(df$bdate,f="%d/%m/%y"),"%d/%m/%Y")` rather than `<-`.
Dirk Eddelbuettel
Thanks, yes I'd copied the strptime statement from a warning that came up when I was trying this out. In fact, it seems the assignment isn't needed at all. Will edit this out.
James
Thank you for the great help!Bazon
Bazon
+2  A: 
df$ddate <- format(as.Date(df$ddate), "%d/%m/%Y")
Brani
Thanks, Brani!Bazon
Bazon
A: 

Default R action is to treat strings as factors. Of course, an individual setup may differ from defaults. It's a good practice to change variable values to character, and then convert it to date. I often use chron package - it's nice, simple and what matters the most, it does the job. Only downside of this package lays in time zone handling.

If you don't have chron installed, do:

 install.packages("chron")
 # load it
 library(chron)
 # make dummy data
 bdate <- c("09/09/09", "12/05/10", "23/2/09")
 wdate <- c("12/10/09", "05/01/07", "19/7/07")
 ddate <- c("2009-09-27", "2007-05-18", "2009-09-02")
 # notice the last argument, it will not allow creation of factors!
 dtf <- data.frame(id = 1:3, bdate, wdate, ddate, stringsAsFactors = FALSE)
 # since we have characters, we can do:
 foo <- transform(dtf, bdate = chron(bdate, format = "d/m/Y"), wdate = chron(wdate, format = "d/m/Y"), ddate = chron(ddate, format = "y-m-d"))
 # check the classes
 sapply(foo, class)
 # $id
 # [1] "integer"

 # $bdate
 # [1] "dates" "times"

 # $wdate
 # [1] "dates" "times"

 # $ddate
 # [1] "dates" "times"

C'est ca... it should do the trick...

aL3xa