提取Rcpp中的矩阵行

问题描述 投票:0回答:1

我跟随Rcpp Quick Reference Guide提取矩阵的一行作为矢量。该指南的示例是:

// Copy the second column into new object (xx is a NumericMatrix)
NumericVector zz1 = xx( _, 1);

当我在Rstudio中获取以下代码时,收到以下错误:

enter image description here

#include <Rcpp.h>
using namespace Rcpp;


// [[Rcpp::export]]
int foo1(Rcpp::IntegerVector res)
{
  int output = res[0];
  return output;
}


// [[Rcpp::export]]
int foo(Rcpp::IntegerMatrix res)
{
  int n = res.nrow();
  int output;
  IntegerVector temp_res = res( 1, _);
  // IntegerVector temp_res = res.row(1);

  for (int r = 0; r < n; r++) {
    output = foo1(res = temp_res); ////////   Line 22
    // output = foo1(res = as<IntegerVector>(temp_res));
  }
  return output;
}

为什么会出现此错误?如何从矩阵中提取所需的行并将其用于另一个函数,如上所示?

r rcpp
1个回答
0
投票

子集不是错误的来源。实际上,这是由于第一个错误而触发的更高版本的错误。

话虽如此,运行代码将产生:

fileb9516da5f592.cpp:22:23: error: no viable overloaded '='
    output = foo1(res = temp_res); ////////   Line 22
                  ~~~ ^ ~~~~~~~~
/Library/Frameworks/R.framework/Versions/3.6/Resources/library/Rcpp/include/Rcpp/vector/Matrix.h:83:13: note: candidate function not viable: no known conversion from 'Rcpp::IntegerVector' (aka 'Vector<13>') to 'const Rcpp::Matrix<13, PreserveStorage>' for 1st argument
    Matrix& operator=(const Matrix& other) {
            ^
/Library/Frameworks/R.framework/Versions/3.6/Resources/library/Rcpp/include/Rcpp/vector/Matrix.h:90:13: note: candidate function not viable: no known conversion from 'Rcpp::IntegerVector' (aka 'Vector<13>') to 'const SubMatrix<13>' for 1st argument
    Matrix& operator=( const SubMatrix<RTYPE>& ) ;
            ^
1 error generated.
make: *** [fileb9516da5f592.o] Error 1
clang++ -std=gnu++11 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG   -I"/Library/Frameworks/R.framework/Versions/3.6/Resources/library/Rcpp/include" -I"/private/var/folders/b0/vt_1hj2d6yd8myx9lwh81pww0000gn/T/RtmpRe7iKX/sourceCpp-x86_64-apple-darwin15.6.0-1.0.3" -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -I/usr/local/include  -fPIC  -Wall -g -O2  -c fileb9516da5f592.cpp -o fileb9516da5f592.o

注意,第一个错误是:

fileb9516da5f592.cpp:22:23: error: no viable overloaded '='
    output = foo1(res = temp_res); ////////   Line 22
                  ~~~ ^ ~~~~~~~~

由于命名参数传递,代码抛出错误。与R不同,C ++不支持命名参数。解决方法是使用位置参数。

即更改:

    output = foo1(res = temp_res); ////////   Line 22

至:

    output = foo1(temp_res); ////////   Line 22

Voila!

foo(matrix(1:4))
#[1] 2
© www.soinside.com 2019 - 2024. All rights reserved.