简体   繁体   中英

Max date of DateVector in Rcpp

How to save the maximum date within a DateVector as a variable in Rcpp?

The toy example below returns the error message:

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 an iterator; you need to dereference it to get the underlying value:

#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"

*/

Alternatively, treat your input as an ordinary NumericVector and use Rcpp::max :

// [[Rcpp::export]]
Date MaxDate(DataFrame d) {
    NumericVector dte = d["date"];
    return Date(Rcpp::max(dte));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM