首页 > 解决方案 > 在构造时用单个值填充 NumericMatrix

问题描述

我正在尝试在构造时用单个值填充 NumericMatrix。例如,考虑以下情况:

#include <Rcpp.h>
using namespace Rcpp;

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

这是抛出的错误:

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){
    ^

为什么NumericMatrix无法在固定尺寸旁边用单个值实例化?

标签: rcpp

解决方案


所以简而言之,这是可行的(一条较长的线分成三段以供显示):

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

但是没有使用行的匹配构造函数,矩阵的列。所以你必须使用上面给你的向量,并手动设置尺寸。

例如 via

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

推荐阅读