[R] Converting date vector into a serial date number

Jeff Newmiller
Tue, 04 Apr 2017 15:16:02 -0000

I think it is important to point out that treating dates or times as serial
numbers should only be done for importing or exporting data. Rather, once the
conversion to one of the ?DateTimeClasses has occurred you are better off
leaving it as such to reduce the brittleness of your code. For one thing, you
should not be writing code that makes assumptions about the epoch (zero offset)
everywhere in your code.
--
Sent from my phone. Please excuse my brevity.

On April 4, 2017 8:00:25 AM PDT, Marc Schwartz <marc_schwartz at me.com>
wrote:
>
>> 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
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.