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

标签 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);
}

最佳答案

你很接近。索引仅使用 [] -- 参见 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/

相关文章:

r - 防止 plot.gam 生成图形

r - 在Docker Plumber中使用R预测包

r - Markdown表到R中的数据框

c++ - sugar all() 行的 Rcpp 错误

c++ - Rcpp:如何将复数从 R 传递到 cpp

r - `geom_abline` 和 `facet_wrap` 似乎不兼容

regex - 删除R中的小数

r - 从 Rcpp ( Armadillo ) 调用 glmnet

r - 如何通过多个for循环使Rcpp代码高效?

r - 在其他 c++ 函数中使用 c++ 函数(在带有 Rcpp 的 R 包中)