Wednesday, June 8, 2011

R - converting integers or strings into date format

  • as.Date(x,format="")
  • dates are given in a lot of different formats, e.g.
    • "2011-03-14"
    • "2011-Mar-14"
    • "11-March-14"
  • if you want to convert them you have to tell R which format your dates have, here some examples:
  • > as.Date("2011-03-14",format="%Y-%m-%d")
    [1] "2011-03-14"
    > as.Date("2011/03/14", format="%Y/%m/%d")
    [1] "2011-03-14"
    > as.Date("14.3.2011", format="%d.%m.%Y")
    [1] "2011-03-14"
    > as.Date("2011-Sep-14", format="%Y-%b-%d")
    [1] "2011-09-14"
    > as.Date("2011-september-14", format="%Y-%B-%d")
    [1] "2011-09-14"
    > as.Date("14. November 1999", format="%d. %B %Y")
    [1] "1999-11-14"
  • here are the codes:
    Code Value
    %d Day of the month (decimal number)
    %m Month (decimal number)
    %b Month (abbreviated)
    %B Month (full name)
    %y Year (2 digits)
    %Y Year (4 digits)
  • if the date is given as integer you have to specify the origin - R counts in days. e.g. in SPSS  a date is stored in seconds, the origin is 1582-10-14. So you have divide by 86400 (=24*60*60); for example if 1000000 is given the command is:
  • > as.Date(1000000/86400, origin="1582-10-14")
    [1] "1582-10-25"

     the origin in Excel: 1900-01-01; SAS: 1960-01-01; R: 1970-01-01 

No comments :

Post a Comment