Search code examples
rcpp

Fill a NumericMatrix with a single value on construction


I'm trying to fill a NumericMatrix with a single value on construction. As an example, consider the following:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void test() {
  NumericMatrix res(1, 1, NA_REAL);
}

This is throwing the error of:

error: call to constructor of 'Vector<14, PreserveStorage>' is ambiguous
        VECTOR( start, start + (static_cast<R_xlen_t>(nrows_)*ncols) ),
        ^       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
file46e92f4e027d.cpp:6:17: note: in instantiation of function template specialization 'Rcpp::Matrix<14, PreserveStorage>::Matrix<double>' requested here
  NumericMatrix res(1, 1, NA_REAL);

/Library/Frameworks/R.framework/Versions/4.0/Resources/library/Rcpp/include/Rcpp/vector/Vector.h:88:5: note: candidate constructor [with T = double]
    Vector( const T& size, const stored_type& u,
    ^
/Library/Frameworks/R.framework/Versions/4.0/Resources/library/Rcpp/include/Rcpp/vector/Vector.h:211:5: note: candidate constructor [with InputIterator = double]
    Vector( InputIterator first, InputIterator last){
    ^

Why is a NumericMatrix unable to be instantiated with a single value alongside fixed dimensions?


Solution

  • So in short this works (one longer line broken in three for display):

    > Rcpp::cppFunction("NumericVector fp() { 
    +     NumericVector res(3,NA_REAL); 
    +     return res;}")
    > fp()
    [1] NA NA NA  
    >  
    

    but there is no matching constructor using rows, cols for matrices. So you have to use what vectors give you above, and set dimensions by hand.

    For example via (where I had it all in one line which I broke up here for exposition)

    > Rcpp::cppFunction("NumericMatrix fp(int n, int k) { 
    +         NumericVector res(n*k,NA_REAL); 
    +         res.attr(\"dim\") = IntegerVector::create(n,k); 
    +         return NumericMatrix(res);}")
    > fp(2,3)
         [,1] [,2] [,3]
    [1,]   NA   NA   NA
    [2,]   NA   NA   NA
    >