我想访问不连续的矩阵元素,然后将子选择传递给(例如)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);
}
最佳答案
你很接近。索引仅使用 []
-- 参见 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>
关于r - 通过整数向量进行矩阵索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56739765/