Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date in the form: 20120405

Tags:

date

r

Apologies for the simple question, but I can't find help for this type of date.

April 5th, 2012 is saved as numeric as "20120405"

How can I convert a vector of such values into usable dates?

like image 720
Charlie Avatar asked Apr 05 '12 08:04

Charlie


3 Answers

You just need the as.Date function:

R> x = "20120405"
R> as.Date(x, "%Y%m%d")
[1] "2012-04-05"

Look at the help file: ?as.Date, but essentially

  • %Y means year in the form 2012, use %y for 12.
  • %m is the month.
  • %d the day.

If your date had separators, say, 2012-04-05, then use something like: %Y-%m-%d. Alternatively, you can use:

R> strptime(x, "%Y%m%d")
[1] "2012-04-05"

In particular, you can pass vectors of dates to these functions, so:

R> y = c("20120405", "20121212")
R> as.Date(y, "%Y%m%d")
[1] "2012-04-05" "2012-12-12"
like image 68
csgillespie Avatar answered Oct 16 '22 03:10

csgillespie


like this,

(foo <- as.Date("20120405", "%Y%m%d"))
# "2012-04-05"

and maybe you want to format to get the month printed out

format(foo, "%Y %b %d")
# "2012 Apr 05"

You could take a look at this page

like image 41
Eric Fail Avatar answered Oct 16 '22 03:10

Eric Fail


With strptime you can convert it to POSIXlt class and with as.Date you can convert it to a Date class using format "%Y%m%d":

strptime( "20120405",format="%Y%m%d")
[1] "2012-04-05"

as.Date( "20120405",format="%Y%m%d")
[1] "2012-04-05"

Edit:

It is not really clear if you have character "20120405" or numeric 20120405. In the latter case you have to convert to character first with as.character(20120405)

like image 3
Sacha Epskamp Avatar answered Oct 16 '22 03:10

Sacha Epskamp