将列表导入Rcpp

时间:2017-12-19 14:18:42

标签: r rcpp

我在R中有一个列表(里面有列表),需要使用Rcpp导入到C。

# R
MainList <- list()
MainList$myint <- 2
MainList$mylist <- list(matrix(1,2,2), matrix(2,2,2))
MainList

我的目标是导入R中的列表(示例中为MainList $ mylist)并复制到C中的一个3D数组。

我试过了:

// Rcpp

// [[Rcpp::export]]
List MyFunction (List MainList){  
    int N =  as<int>(MainList["myint"]);
    List mylistRcpp = as<List>(MainList["mylist"]); // It this work? Apparently no

    double*** mylistC; // already with allocate memory

    for (int h=0; h<N; h++){
        NumericMatrix temp = mylistRcpp[h];
        for (int i=0; i<N; i++){
            for (int n=0; n<N; n++){
                mylistC[h][i][n] = temp(i, n);
            }
        }
    }


    return List::create(Named("1") = N,
                        Named("2") = N);
    }

我可以这样导入列表吗?有一些简单的方法可以一个一个地复制没有副本吗?我需要3D数组用于另一个功能。我不确定如何将列表从R导入Rcpp。

1 个答案:

答案 0 :(得分:0)

是的,您可以在Rcpp :: List中插入一个Rcpp :: List,并根据需要递归。不需要双**和其他体操。

代码

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::List ListExample() {

  std::string abc   = "def";
  double tol        = 0.001;

  Rcpp::List l = Rcpp::List::create(Rcpp::Named("method", abc),
                                    Rcpp::Named("tolerance", tol));
  Rcpp::List ll = Rcpp::List::create(Rcpp::Named("method", abc),
                                     Rcpp::Named("tolerance", tol),
                                     Rcpp::Named("list", l));
  return ll;
}

/*** R
ListExample()
*/

演示

R> sourceCpp("/tmp/soQ.cpp")

R> ListExample()
$method
[1] "def"

$tolerance
[1] 0.001

$list
$list$method
[1] "def"

$list$tolerance
[1] 0.001


R> 

如您所见,我们在列表中有一个列表。