Learn R Programming

RcppExamples (version 0.1.9)

RcppDateExample: C++ classes for interfacing date and datetime R objects

Description

Rcpp has the classes Rcpp::Date, Rcpp::Datetime, Rcpp::DateVector and Rcpp::DatetimeVector.

Arguments

Details

In the C++ code for the RcppDateExample.cpp file:


        // [[Rcpp::export]]
        List DateExample(DateVector & dv, DatetimeVector & dtv) {
            Function formatDate("format.Date");
            Function formatDatetime("format.POSIXct");

Rprintf("\nIn C++, seeing the following date value\n"); for (int i=0; i<dv.size(); i++) { Rcout << as<std::string>(formatDate(wrap(dv[i]))) << std::endl; dv[i] = dv[i] + 7; // shift a week } Rprintf("\nIn C++, seeing the following datetime value\n"); for (int i=0; i<dtv.size(); i++) { Rcout << as<std::string>(formatDatetime(wrap(dtv[i]))) << std::endl; dtv[i] = dtv[i] + 0.250; // shift 250 millisec }

// Build result set to be returned as a list to R. return List::create(Named("date", dv), Named("datetime", dtv)); }

References

Writing R Extensions, available at https://www.r-project.org.

Examples

Run this code
# NOT RUN {
# set up date and datetime vectors
dvec <- Sys.Date() + -2:2
dtvec <- Sys.time() + (-2:2)*0.5

# call the underlying  C++ function
result <- RcppDateExample(dvec, dtvec)

# inspect returned object
result
# }

Run the code above in your browser using DataLab