在R中定义一个矩阵并将其传递给C++

int*_*try 5 c++ r rcpp

我有一个在R中定义的矩阵.我需要将这个矩阵传递给c ++函数并在C++中进行操作.示例:在R中,定义矩阵,

A <- matrix(c(9,3,1,6),2,2,byrow=T)
PROTECT( A = AS_NUMERIC(A) );
double* p_A = NUMERIC_POINTER(A);
Run Code Online (Sandbox Code Playgroud)

我需要将这个矩阵传递给C++函数,其中类型的变量'data' vector<vector<double>>将用矩阵A初始化.

我似乎无法弄清楚如何做到这一点.我想的是更复杂的方式然后我应该是,我打赌有一个简单的方法来做到这一点.

Pau*_*tra 5

您可能想要使用Rcpp.该软件包允许轻松集成R和C++,包括将对象从R传递到C++.该软件包可在CRAN上获得.此外,CRAN上的一些软件包使用Rcpp,因此它们可以作为灵感来源.Rcpp的网站在这里:

http://dirk.eddelbuettel.com/code/rcpp.html

其中包括一些教程.


Rom*_*ois 5

正如保罗所说,我会建议Rcpp用于那种事情.但这也取决于你想要的vector< vector<double> >意思.假设您要存储列,您可以像这样处理矩阵:

require(Rcpp)
require(inline)

fx <- cxxfunction( signature( x_ = "matrix" ), '
    NumericMatrix x(x_) ;
    int nr = x.nrow(), nc = x.ncol() ;
    std::vector< std::vector<double> > vec( nc ) ;
    for( int i=0; i<nc; i++){
        NumericMatrix::Column col = x(_,i) ;
        vec[i].assign( col.begin() , col.end() ) ;
    }
    // now do whatever with it
    // for show here is how Rcpp::wrap can wrap vector<vector<> >
    // back to R as a list of numeric vectors
    return wrap( vec ) ;
', plugin = "Rcpp" )
fx( A )
# [[1]]
# [1] 9 1
# 
# [[2]]
# [1] 3 6    
Run Code Online (Sandbox Code Playgroud)

  • Rcpp太棒了:) (3认同)