Changing date format to "%d/%m/%Y"

99,098

Solution 1

df$ddate <- format(as.Date(df$ddate), "%d/%m/%Y")

Solution 2

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")

Solution 3

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...

Share:
99,098
Bazon
Author by

Bazon

Updated on July 09, 2022

Comments

  • Bazon
    Bazon almost 2 years

    Would like to change the date format. My data frame is shown below and would like to change all the date formats to "%d/%m/%Y".

    df:

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