Using Rcout for output synchronised with R

January 8, 2013

(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:

The value is 1.23

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)
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
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 their blog: Rcpp Gallery. 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)