Rcpp 中 DateVector 的最大日期
Max date of DateVector in Rcpp
如何将 DateVector 中的最大日期保存为 Rcpp 中的变量?
下面的玩具示例returns错误信息:
no viable conversion from '__gnu_cxx::__normal_iterator<Rcpp::Date
*, std::vector<Rcpp::Date, std::allocator<Rcpp::Date> > >' to 'NumericVector' (aka 'Vector<14>')
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
Date date_toy_example(DataFrame d){
// Get date vector from data frame
DateVector dte = d["date"];
// Get max date
Date max_dte = std::max_element(dte.begin(), dte.end());
// Return maximum date
return max_dte;
}
// R code
/*** R
df <- data.frame(id=1:10, date=seq(as.Date("2015-01-01"),as.Date("2015-01-10"), by="day"))
date_toy_example(df)
*/
std::max_element
returns 一个迭代器;您需要取消引用它以获得基础值:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
Date MaxDate(DataFrame d) {
DateVector dte = d["date"];
Date max_dte = *std::max_element(dte.begin(), dte.end());
// ^^^
return max_dte;
}
/*** R
df <- data.frame(
id=1:10,
date = seq(as.Date("2015-01-01"),
as.Date("2015-01-10"),
by="day")
)
MaxDate(df)
# [1] "2015-01-10"
max(df$date)
# [1] "2015-01-10"
*/
或者,将您的输入视为普通 NumericVector
并使用 Rcpp::max
:
// [[Rcpp::export]]
Date MaxDate(DataFrame d) {
NumericVector dte = d["date"];
return Date(Rcpp::max(dte));
}
如何将 DateVector 中的最大日期保存为 Rcpp 中的变量?
下面的玩具示例returns错误信息:
no viable conversion from '__gnu_cxx::__normal_iterator<Rcpp::Date *, std::vector<Rcpp::Date, std::allocator<Rcpp::Date> > >' to 'NumericVector' (aka 'Vector<14>')
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
Date date_toy_example(DataFrame d){
// Get date vector from data frame
DateVector dte = d["date"];
// Get max date
Date max_dte = std::max_element(dte.begin(), dte.end());
// Return maximum date
return max_dte;
}
// R code
/*** R
df <- data.frame(id=1:10, date=seq(as.Date("2015-01-01"),as.Date("2015-01-10"), by="day"))
date_toy_example(df)
*/
std::max_element
returns 一个迭代器;您需要取消引用它以获得基础值:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
Date MaxDate(DataFrame d) {
DateVector dte = d["date"];
Date max_dte = *std::max_element(dte.begin(), dte.end());
// ^^^
return max_dte;
}
/*** R
df <- data.frame(
id=1:10,
date = seq(as.Date("2015-01-01"),
as.Date("2015-01-10"),
by="day")
)
MaxDate(df)
# [1] "2015-01-10"
max(df$date)
# [1] "2015-01-10"
*/
或者,将您的输入视为普通 NumericVector
并使用 Rcpp::max
:
// [[Rcpp::export]]
Date MaxDate(DataFrame d) {
NumericVector dte = d["date"];
return Date(Rcpp::max(dte));
}