首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >理解通过RInside将armadillo矩阵传递给R函数

理解通过RInside将armadillo矩阵传递给R函数
EN

Stack Overflow用户
提问于 2012-11-14 23:37:19
回答 2查看 1.2K关注 0票数 4

我正在尝试通过RInside在C++中使用R。我在向R传递armadillo矩阵并返回结果时遇到了问题。下面我可以从一个R库函数返回一个结果,但是我得到了错误的结果。我正在使用moments包中的skewness函数作为示例,它在R中正常工作。我检查了RInside中的示例,但我仍然不确定如何使用RcppArmadillo。我如何正确地将c++中的armadillo矩阵传递给R?

代码语言:javascript
复制
    #include <RInside.h>                   
    #include <RcppArmadillo.h>

    using namespace std;
    using namespace arma;

    int main(int argc, char *argv[]) {
        RInside R(argc, argv);  


        string R_libs = "suppressMessages(library(moments));";

        R.parseEvalQ(R_libs);

        mat A = randu<mat>(5,5);

        R["A"] = A;

        string R_skewness = "B <- skewness(A);";
        //this fails
        mat B = Rcpp::as<mat>(R.parseEval(R_skewness)); //terminate called after throwing an instance of 'Rcpp::not_a_matrix'   

        //this works but wrong
        mat B = Rcpp::as<vec>(R.parseEval(R_skewness)); // returns only 1 number, should be 5 ( 1 for each columnn), same result if i change mat B to vec B
        exit(0);
 }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-11-15 00:03:46

我们实现as<mat>的方式要求你传递的R对象是一个矩阵。在您的示例中,B是一个向量:

代码语言:javascript
复制
> A <- matrix( runif(25), ncol = 5)
> A
           [,1]      [,2]       [,3]       [,4]      [,5]
[1,] 0.19215339 0.5857249 0.14345222 0.32154176 0.6162155
[2,] 0.95753898 0.9618379 0.06239842 0.06200197 0.7044018
[3,] 0.33575790 0.1372804 0.03027635 0.62662467 0.9778451
[4,] 0.16504957 0.1919765 0.49176372 0.94841456 0.2914772
[5,] 0.01570709 0.8055231 0.51218581 0.79562809 0.6939380
> B <- skewness( A )
> B
[1]  1.15196587 -0.04547576  0.32186257 -0.30788111 -0.29251009

对于转换到arma::vec,我不会重现您看到的行为。arma::vec有3个元素:

代码语言:javascript
复制
require( RcppArmadillo )    ## and make sure you have Rcpp 0.10.0 or later

sourceCpp( code = '
// [[Rcpp::depends("RcppArmadillo")]]

#include <RcppArmadillo.h>

using namespace arma ; 
using namespace Rcpp ;

// [[Rcpp::export]]
List foo( NumericVector x){
    vec B = Rcpp::as<vec>(x); 

    return List::create( 
        _["nrows"] = B.n_rows,
        _["ncols"] = B.n_cols
    ) ;

}
')
foo( c(1, 2, 3 ) )
# $nrows
# [1] 3
# 
# $ncols
# [1] 1
票数 5
EN

Stack Overflow用户

发布于 2012-11-14 23:53:18

您正在尝试涉及几个大量模板化的库的复合表达式。这可能会出错。我建议把它分成几个部分:

确保你有你期望的矩阵A传递给嵌入式R

  • 确保函数调用工作正常,检查result.

  • Important:检查结果类型。矩阵应该会很好地返回。

  • 将结果返回给C++。

  • 将结果返回给Rcpp。

  • 使用RcppArmadillo编组到达Armadillo。

原则上,这应该是可行的。问题在于细节,一如既往。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13381975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档