Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rcpp error comparing a DateVector element with a Date

Tags:

r

rcpp

The following Rcpp function doesn't compile:

// [[Rcpp::export]]
bool dateProb(DateVector dateVec, Date date) {
  return (dateVec[0] < date);
}

I get the error message:

Use of overloaded operator '<' is ambiguous (with operand types 'typename storage_type<14>::type' (aka 'double') and 'Rcpp::Date)

What am I doing wrong? Why doesn't dateVec[0] have the type Rcpp::Date?

like image 737
jms202 Avatar asked Mar 06 '26 13:03

jms202


1 Answers

Well, an Rcpp::DateVector is not a vector of Rcpp::Dates, but is a class derived from Rcpp::NumericVector (see here). This makes sense considering R's own internal treatment of date vectors:

pryr::sexp_type(as.Date("2019/05/04"))
# [1] "REALSXP"

So, it may seem surprising at first, but is no real impediment. You can just do this:

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
bool dateProb(DateVector dateVec, Date date) {
    Date date2 = dateVec(0);
    return (date2 < date);
}

This compiles just fine, and gives the expected answer from R:

x <- as.Date("2019/05/04")
y <- as.Date("2019/05/03")
dateProb(x, y)
# [1] FALSE

dateProb(y, x)
# [1] TRUE

If what you actually want is a vector of Rcpp::Dates, that can be achieved easily as well using the member function getDates():

// [[Rcpp::export]]
bool dateProb(DateVector dateVec, Date date) {
    Date date2 = dateVec(0);
    std::vector<Date> newdates = dateVec.getDates();
    Rcpp::Rcout << (newdates[0] < date) << "\n";
    return (date2 < date);
}

/*** R
x <- as.Date("2019/05/04")
y <- as.Date("2019/05/03")
dateProb(x, y)
dateProb(y, x)
*/

> x <- as.Date("2019/05/04")

> y <- as.Date("2019/05/03")

> dateProb(x, y)
0
[1] FALSE

> dateProb(y, x)
1
[1] TRUE

Or by just specifying that as your input:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
bool dateProb(std::vector<Date> dateVec, Date date) {
    return (dateVec[0] < date);
}

/*** R
x <- as.Date("2019/05/04")
y <- as.Date("2019/05/03")
dateProb(x, y)
dateProb(y, x)
*/

> x <- as.Date("2019/05/04")

> y <- as.Date("2019/05/03")

> dateProb(x, y)
[1] FALSE

> dateProb(y, x)
[1] TRUE
like image 55
duckmayr Avatar answered Mar 08 '26 03:03

duckmayr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!