[R] Converting date vector into a serial date number
jdnewmil at dcn.davis.ca.us
Tue Apr 4 17:16:02 CEST 2017
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>
>> 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
>> 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.
>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
>So your 'b' should be 3, not 2, presuming the first of the month is
>> as.Date(683401, origin = "1970-01-01") - 719529
>So, to reverse it, would be:
>a <- 1871
>b <- 3
>> paste(a, b, 1, sep = "-")
>> as.Date(paste(a, b, 1, sep = "-"))
>> as.numeric(as.Date(paste(a, b, 1, sep = "-"))) + 719529
>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.
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.
More information about the R-help