A second example of using Boost

January 15, 2013

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

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 write this post on a machine with Boost headers in a standard system location. So stuff just works. If you have to install Boost from source, and into a non-standard location, you may need to add a -I flag, not unlike how added the C++11 flag in this post .

#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<double> lexicalCast(std::vector<std::string> v) {

    std::vector<double> res(v.size());

    for (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;

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:

v <- c("1.23", ".4", "1000", "foo", "42", "pi/4")
[1]    1.23    0.40 1000.00      NA   42.00      NA

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

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, 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.


Mango solutions

RStudio homepage

Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training



CRC R books series

Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)