[R] Converting date vector into a serial date number

Marc Schwartz marc_schwartz at me.com
Tue Apr 4 17:00:25 CEST 2017


> On Apr 4, 2017, at 8:51 AM, Tunga Kantarcı <tungakantarci at gmail.com> wrote:
> 
> I have a data frame. One column (call this column a) contains years,
> like 1871, and another column (call this column b) contains months,
> like 2. I need to convert these year-month combinations, stored in
> these two date vectors, into a single serial date number. E.g. year
> 1871 and month 2, stored in different vectors, should return 683429.
> Meanwhile, when I check the class type of columns a and b, they are
> both integer.
> 
> In MATLAB this can easily be done using the syntax
> 
> output = datenum(a,b,1)
> 
> In R, I have tried the as.POSIXct function but did not succeed. I also
> tried the ISOdatetime function but that returned NA for all entries.
> It should be a simple operation but I cannot seem to figure it out.

Hi,

The standard date classes in R require the full date (day, month, year) and the date/time classes require a correct time as well.

Looking at the help page for ?as.Date, there is information pertaining to MATLAB's date origin of 0000-01-01, as compared to R's of 1970-01-01. The difference is an offset of 719529.

Taking your number above of 683429, that would yield:

 > as.Date(683429, origin = "1970-01-01") - 719529
[1] "1871-03-01"

So your 'b' should be 3, not 2, presuming the first of the month is inferred. Otherwise:

> as.Date(683401, origin = "1970-01-01") - 719529
[1] "1871-02-01"

So, to reverse it, would be:

a <- 1871
b <- 3

> paste(a, b, 1, sep = "-")
[1] "1871-3-1"

> as.Date(paste(a, b, 1, sep = "-"))
[1] "1871-03-01"

> as.numeric(as.Date(paste(a, b, 1, sep = "-"))) + 719529
[1] 683429
  
The last step takes the date and coerces it to a numeric value in the number of days since the origin.

More generally, if you Google for R MATLAB, there are some online references that provide varying levels of function mappings between the two languages that you may find helpful.

Regards,

Marc Schwartz



More information about the R-help mailing list