title | author | license | tags | summary | layout | src |
---|---|---|---|---|---|---|
A second example of using Boost |
Dirk Eddelbuettel |
GPL (>= 2) |
basics boost |
This post shows how to use some string functionality from Boost |
post |
2013-01-15-a-second-boost-example.cpp |
We introduced Boost in a first post doing some integer math. In this post we want to look at the very versatile Boost.Lexical_Cast library to convert text to numbers -- see the Motivation for more.
As before, I should note that I initially wrote this post on a machine with Boost
in a standard system location. So stuff just works. Others may have had to install Boost from source,
and into a non-standard location, which may have required an -I
flag,
not unlike how we initially added
the C++11 flag in this post before the corresponding plugin was added.
This is now automated thanks to the BH package which, if installed, provides Boost headers for use by R in compilations just like this one.
{% highlight cpp %} // We can now use the BH package // [[Rcpp::depends(BH)]]
#include <Rcpp.h> #include <boost/lexical_cast.hpp> // one file, automatically found for me
using namespace Rcpp;
using boost::lexical_cast; using boost::bad_lexical_cast;
// [[Rcpp::export]] std::vector lexicalCast(std::vectorstd::string v) {
std::vector<double> res(v.size());
for (unsigned int i=0; i<v.size(); i++) {
try {
res[i] = lexical_cast<double>(v[i]);
} catch(bad_lexical_cast &) {
res[i] = NA_REAL;
}
}
return res;
} {% endhighlight %}
This simple program uses the exceptions idiom we
discussed to branch: when a value cannot
be converted, a NA
value is inserted.
We can test the example:
{% highlight r %} v <- c("1.23", ".4", "1000", "foo", "42", "pi/4") lexicalCast(v) {% endhighlight %}
[1] 1.23 0.40 1000.00 NA 42.00 NA