2

I have a dataset, where the dates are given in three columns: year, month, day. I want to convert this to the standard R date format (i.e. days since 1-1-1970). Right now I have this:

date <- as.Date(paste(year,month,day, sep="-"))

However I am wondering if this is the correct way / if there is a more efficient way.

Bastiaan Quast
  • 2,802
  • 1
  • 24
  • 50
  • Please post a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Also, what do you mean by efficient? – Ari B. Friedman Dec 02 '12 at 13:32
  • My question is basically, is this the way you would expect this to be done, or is there a specific function / method for this. – Bastiaan Quast Dec 02 '12 at 13:59

2 Answers2

6

The as.Date function represents a date as the number of days since Jan 1, 1970. Unix time refers to the number of seconds since Jan 1, 1970. You'll want to use the as.POSIXct function and then convert it to a numeric object:

as.double(as.Date(paste(year, month, day, sep="-"))) # days since 1970-1-1
as.double(as.POSIXct(as.Date(paste(year, month, day, sep="-")))) # seconds since 1970-1-1
Erik Shilts
  • 4,389
  • 2
  • 26
  • 51
2

That's pretty much the standard way to do this. In fact, if you look at the code of ISOdatetime you can see that it uses a similar algorithm.

Roland
  • 127,288
  • 10
  • 191
  • 288