3

我想转换一个列表,例如:

[[1]]
[1]   3   4  99   1 222

[[2]]
[1] 1 2 3 4 5

到 Rcpp 中的矩阵 (2,5)。最快的方法是什么?

在这种情况下,函数 wrap() 不起作用。

首先,我尝试将列表转换为向量,然后再转换为矩阵。在函数中使用 wrap():

#include <Rcpp.h>
using namespace Rcpp ;


// [[Rcpp::export]]
NumericVector mat(List a){
  NumericVector wynik;
  wynik = Rcpp::wrap(a);
  return wynik;
}

  /***R
  mat(list(c(3,4,99,1,222), c(1,2,3,4,5)))
  */ 

我收到一个错误:

>   mat(list(c(3,4,99,1,222), c(1,2,3,4,5)))
Error in eval(substitute(expr), envir, enclos) : 
  not compatible with requested type
4

2 回答 2

4

与其cbindt进行一次迭代,不如初始化一个矩阵,然后用必要的维度检查逐行填充。

代码

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericMatrix make_mat(Rcpp::List input_list){

  unsigned int n = input_list.length();

  if(n == 0) { 
    Rcpp::stop("Must supply a list with more than 1 element.");
  }

  Rcpp::NumericVector testvals = input_list[0];
  unsigned int elems = testvals.length();

  Rcpp::NumericMatrix result_mat = Rcpp::no_init(n, elems);

  // fill by row
  for(unsigned int i = 0; i < n; i++) {
    Rcpp::NumericVector row_val = input_list[i];

    if(elems != row_val.length()) {
      Rcpp::stop("Length of row does not match matrix requirements"); 
    }

    result_mat(i, Rcpp::_) = row_val;

  }

  return result_mat;
}

结果

make_mat(list(c(3,4,99,1,222), c(1,2,3,4,5)))
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    3    4   99    1  222
# [2,]    1    2    3    4    5
于 2016-12-11T09:20:14.887 回答
2

我使用了糖函数Rcpp::cbindRcpp::transpose.

编码:

#include <Rcpp.h>
using namespace Rcpp ;


// [[Rcpp::export]]
NumericMatrix mat(List a){
  NumericVector a1;
  NumericVector a0;
  NumericMatrix b;
  a1 = a[1];
  a0 = a[0];
  b = Rcpp::cbind(a0, a1);
  b = Rcpp::transpose(b);
  return b;
}

我们收到:

>   mat(list(c(3,4,99,1,222), c(1,2,3,4,5)))
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    4   99    1  222
[2,]    1    2    3    4    5
于 2016-12-11T08:47:25.570 回答