[英]Rcpp error comparing a DateVector element with a Date
The following Rcpp function doesn't compile: 以下Rcpp函数无法编译:
// [[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)
重载运算符“ <”的使用是模棱两可的(操作数类型为“ typename storage_type <14> :: type”(又名“ double”)和“ Rcpp :: Date”)
What am I doing wrong? 我究竟做错了什么? Why doesn't
dateVec[0]
have the type Rcpp::Date
? 为什么
dateVec[0]
具有Rcpp::Date
类型?
Well, an Rcpp::DateVector
is not a vector of Rcpp::Date
s, but is a class derived from Rcpp::NumericVector
(see here ). 嗯,
Rcpp::DateVector
不是Rcpp::Date
的向量,而是一个派生自Rcpp::NumericVector
(请参见此处 )。 This makes sense considering R's own internal treatment of date vectors: 考虑到R对日期向量的内部处理,这是有道理的:
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: 这样编译就可以了,并给出了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::Date
s, that can be achieved easily as well using the member function getDates()
: 如果您真正想要的是
Rcpp::Date
的向量,则可以使用成员函数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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.