Using Rcout for output synchronised with R

January 8, 2013
By

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

The Writing R Extensions manual, which provides the gold standard of documentation as far as extending R goes, suggests to use Rprintf and REprintf for output (from C/C++ code) as these are matched to the usual output and error streams maintained by R itself.

Also, use of std::cout and std::cerr (as common in standard C++ code) is flagged when running R CMD check and no longer permitted when uploading to CRAN.

Thanks to an initial patch by Jelmer Ypma, which has since been reworked and extended, we have devices Rcout (for standard output) and Rcerr (for standard error) which intercept output and redirect it to R.

To illustrate, we create a simple function which prints a value:

#include <RcppArmadillo.h>   // as we use RcppArmadillo below
                             // this first example use only Rcpp 

using namespace Rcpp;

// [[Rcpp::export]]
void showValue(double x) {
    Rcout << "The value is " << x << std::endl;
}

We can use this from R, and output will be properly synchronised:

cat("Before\n")
Before
showValue(1.23)
The value is 1.23
cat("After\n")
After

As of the 0.10.* releases, Rcpp itself still lacks the converter code to print simple non-scalar data structures—but RcppArmadillo can do so as Conrad permitted a hool for us to supply the Rcout device as the default device

#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
void showMatrix(arma::mat X) {
    Rcout << "Armadillo matrix is" << std::endl << X << std::endl;
}
M <- matrix(1:9,3,3)
print(M)
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
showMatrix(M)
Armadillo matrix is
   1.0000   4.0000   7.0000
   2.0000   5.0000   8.0000
   3.0000   6.0000   9.0000

Having output from R and C++ mix effortlessly is a very useful feature. We hope to over time add more features to output more of Rcpp basic objects. Patches are of course always welcome.

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.