Search code examples
c++rrcpprcpparmadillo

How to return objects of different types from RcppArmadillo function


l would like to return objects of different types from the function RcppArmadillo.

For example, below is a code where I've tried returning both a vector and function using std::tuple.

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

using namespace arma;

// [[Rcpp::export]]
std::tuple<arma::vec, arma::mat> test_tuple(arma::vec avec, arma::mat amat) {

  arma::vec bvec = avec;
  arma::mat bmat = amat;
  return std::make_tuple(bvec, bmat);
}

However, I get the following error:

static assertion failed: cannot convert type to SEXP

I also tried unsuccessfully using List::create as suggested here:

How to return multiple objects from Rcpp back to R?

How correctly return objects of different types and fix the above error?


Solution

  • I'm not sure what you mean by "tried unsuccessfully" to use List::create. Does the following work for you?

    #include <RcppArmadillo.h>
    // [[Rcpp::depends(RcppArmadillo)]]
    
    // [[Rcpp::export]]
    Rcpp::List test_tuple(arma::vec avec, arma::mat amat) {
    
      arma::vec bvec = avec;
      arma::mat bmat = amat;
      return Rcpp::List::create(
        Rcpp::Named("avec") = avec,
        Rcpp::Named("amat") = amat
      );
    }