通过整数向量进行矩阵索引

时间:2019-06-24 15:28:10

标签: r rcpp

我想访问非连续的矩阵元素,然后将子选择传递给(例如)sum()函数。在下面的示例中,我收到有关无效转换的编译错误。 我对Rcpp相对较新,因此我相信答案很简单。也许我缺少某种演员表?

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins("cpp11")]]

double sumExample() {
    // these are the matrix row elements I want to sum (the column in this example will be fixed)
    IntegerVector a = {2,4,6}; 
    // create 10x10 matrix filled with random numbers [0,1]
    NumericVector v = runif(100);
    NumericMatrix x(10, 10, v.begin()); 
    // sum the row elements 2,4,6 from column 0
    double result = sum( x(a,0) );
    return(result);
}

1 个答案:

答案 0 :(得分:3)

你很近。索引仅使用[](请参阅this write up at the Rcpp Gallery),而您错过了导出标记。主要问题是复合表达有时对于编译器和模板编程而言太多了。因此,如果您拆开它,它会起作用。

更正的代码

#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins("cpp11")]]

// [[Rcpp::export]]
double sumExample() {
    // these are the matrix row elements I want to sum
    // (the column in this example will be fixed)
    IntegerVector a = {2,4,6};
    // create 10x10 matrix filled with random numbers [0,1]
    NumericVector v = runif(100);
    NumericMatrix x(10, 10, v.begin());
    // sum the row elements 2,4,6 from column 0
    NumericVector z1 = x.column(0);
    NumericVector z2 = z1[a];
    double result = sum( z2 );
    return(result);
}

/*** R
sumExample()
*/

演示

 R> Rcpp::sourceCpp("~/git/stackoverflow/56739765/question.cpp")

 R> sumExample()
 [1] 0.758416
 R>