datedatetimercpprcpp11

Find number of days between two given dates in Rcpp


I'm newbie in Rcpp, but I have a task which's connected with Date and Datetime. Let me have market data in DataFrame in my Rcpp function. So, Date field has formatting like this:

2016-04-19 00:01:00

Dataframe field name which contains Date values is "Date". So, I get 2 vectors:

DatetimeVector datetime = df["Date"];
DateVector pureDate = df["Date"];

Problems:

1) I can't take difference between 2 Date values of Date (I don't know why, but gcc-4.9.3 gives me an error on difference like this:

Date pureDay = pureDate[0];
auto tmp = pureDate[j+1] - pureDay;

error: ambiguous overload for 'operator-' (operand types are 'Rcpp::traits::storage_type<14>::type {aka double}' and 'Rcpp::Date') auto tmp = tmpDate[j+1] - tmpTradeDay;

But if I use code like this:

Date pureDay = pureDate[0];
auto tmp = pureDate[j+1] - pureDate[j];

It works well.

2) How it possible to format an output for Date and Datetime objects? to_string won't format it well - I give a result like this: 1461176460.000000

3) I expected that syntax like Date(datetime[i]) will give me a Date object. But it won't. I know that pureDate[1] - pureDate[0] should have the same Y-M-D value, but they differ for series lag (60 seconds).

Thnxs. Could anyone helps me with these problems?


Solution

  • You seem a little lost, and there are really multiple questions in this one.

    Question 1) will give a short example below.

    Question 2) is mostly about formatting, you may want to look into the class documentation and header; both Date and Datetime have a format() method that works just like the R equivalent or C library function for date(time) formating, the fabled strftime().

    Question 3) is unclear; I am not sure what you are asking. Maybe the answer to question 1) below helps.

    Simple example for question 1:

    #include <Rcpp.h>
    
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    double question1(DateVector dv) {
        double d = dv[1] - dv[0];
        return d;
    }
    
    /*** R
    set.seed(123)
    datevector <- Sys.Date() + cumsum(runif(3)*30);
    datevector
    diff(datevector)
    question1(datevector)
    */
    

    and its outcome:

    R> Rcpp::sourceCpp("/tmp/datequestion.cpp")
    
    R> set.seed(123)
    
    R> datevector <- Sys.Date() + cumsum(runif(3)*30);
    
    R> datevector
    [1] "2018-03-28" "2018-04-21" "2018-05-03"
    
    R> diff(datevector)
    Time differences in days
    [1] 23.6492 12.2693
    
    R> question1(datevector)
    [1] 23.6492
    R> 
    

    Same answer as from R. Your code still has an index calculation, that sometimes confuses the compiler. Making it simpler (ie more steps) often helps.

    Lastly, maybe look at some Rcpp documentation and examples. The RcppExamples package has a function on dates and datetimes ...