简体   繁体   English

Rcpp中DateVector的最大日期

[英]Max date of DateVector in Rcpp

How to save the maximum date within a DateVector as a variable in Rcpp? 如何在DateVector中将最长日期保存为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>') 没有从'__gnu_cxx :: __ normal_iterator <Rcpp :: Date *,std :: vector <Rcpp :: Date,std :: allocator <Rcpp :: Date>>>'到'NumericVector'的可行转换(也称为'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; std::max_element返回一个迭代器; 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 : 或者,将您的输入视为普通的NumericVector并使用Rcpp::max

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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