Search code examples
rrcpprcpparmadillo

RCPP Armadillo: Print integer value in function


New to CPP and RCPP

I am putting together an R package with RCPP.

Here are my steps:

  1. Transfer to directory with package.
  2. Run compileAttributes(pkgdir = ".",verbose=TRUE)
  3. Then run build and install from devtools.

I want one of my CPP functions to print a message whenever it is invoked. So i added :

Rcpp::Rcout << "Hello World!" << std::endl;

I then went through steps 1 to 3 above. But no cigar. Not even a cigarillo.

Ideally, I want it to print out an integer value i, somthing like

Sample code.

Rcpp::Rcout << i << std::endl;

SO far, it compiles and the function runs - but no printout of the dear variable. HELP! An example of my function is below. I suspect there is some standard way to either pass the values to R or to simply print from CPP.

    # include <RcppArmadillo.h>
    // [[Rcpp::depends(RcppArmadillo)]]
    // [[Rcpp::plugins(cpp11)]]

    using namespace Rcpp ;
    arma::mat sillyme (arma::mat FE) {
  
    arma::mat FEE = FE ;
    Rcpp::Rcout << "Hello World!" << std::endl;
    Rcpp::Rcout << FE.n_rows << std::endl;

    return(FEE) ;
    }

Solution

  • On my system (Ubuntu 20.04, R 4.0.0), this works just as expected (after adding a // [[Rcpp::export]] attribute to make sure the function is callable from R):

    sillyme(diag(2))
    # Hello World!
    # 2
    #      [,1] [,2]
    # [1,]    1    0
    # [2,]    0    1