Using Boost via the new BH package

January 31, 2013
By

(This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers)

Earlier today the new BH package arrived on CRAN. Over the years, Jay Emerson, Michael Kane and I had numerous discussions about a basic Boost infrastructure package providing Boost headers for other CRAN packages. JJ and Romain chipped in as well, and Jay finally took the lead by first creating a repo on R-Forge. And now the package is out, so what follows is a little demo.

This example borrows something already implemented in my RcppBDT package which wraps code from Boost Date_Time for R.
Here, we compute the so-called IMM Date – generally the the third Wednesday of the month (in the last month of the quarter). Boost has a function computing the Nth day of the Mth week for a given month in a given year: we use that here with Wednesday and the third week.

The kicker is that Boost uses templates almost exclusively. So by declaring an depends attribute on BH, we ensure that the compilation will see the headers files provided by BH. Which happen to be the Boost headers, as that is what the package does. And that is all it takes.

// Use brandnew CRAN package BH for Boost headers

// [[Rcpp::depends(BH)]]
#include <Rcpp.h>

// One include file from Boost
#include <boost/date_time/gregorian/gregorian_types.hpp>

using namespace boost::gregorian;

// [[Rcpp::export]]
Rcpp::Date getIMMDate(int mon, int year) {
    // compute third Wednesday of given month / year
    date d = nth_day_of_the_week_in_month(nth_day_of_the_week_in_month::third,
                                          Wednesday, mon).get_date(year);
    date::ymd_type ymd = d.year_month_day();
    return Rcpp::wrap(Rcpp::Date(ymd.year, ymd.month, ymd.day));
}

We can test this from R for 2013 by computing the first two:

getIMMDate(3, 2013)
[1] "2013-03-20"
getIMMDate(6, 2013)
[1] "2013-06-19"

And for kicks, the same for 2033:

getIMMDate(3, 2033)
[1] "2033-03-16"
getIMMDate(6, 2033)
[1] "2033-06-15"

The BH package is still pretty raw. For example, yesterday’s Rcpp Gallery post on Boost foreach] does not build as we have not yet included the relevant Boost library. So far, BH reflects the needs of Jay and Mike in their (awesome) bigmemory project and my needs in RcppBDT, and then some. For the rest, let us know what may be missing.

To leave a comment for the author, please follow the link and comment on his blog: Rcpp Gallery.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.