rcpp - 在构造时用单个值填充 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::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
>
推荐阅读
- swift - swift中具有多个参数的函数
- hbase - Kerberos 主体没有预期的格式
- json-server - json-server:不匹配路由的默认 JSON
- javascript - 通过 nodejs 或 reactjs 连接到 iTunes
- model - 吊带型号说明
- phpmyadmin - 无法识别的语句类型。(位置 0 的“WITH”附近)
- angular - 具有简单类型行数据的 ag-grid
- algorithm - Dijkstra 分区算法:特例
- java - 如何使用 Retrofit 和 RxJava Android 发布应用程序/Json 类型
- perl - Perl 子程序不在循环中工作