3

I want to convert a list e.g like this:

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

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

to a matrix (2,5) in Rcpp. What is the fastest way to do this?

Function wrap() is not working in this case.

First of of I have tried to convert a list to a vector and later to a matrix.Using wrap() in a function:

#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)))
  */ 

I receive a bug:

>   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
AgnieszkaTomczyk
  • 253
  • 2
  • 12

2 Answers2

4

Instead of cbind and t for only one iteration, perhaps it would be better to initialize a matrix and then fill by row with the necessary dimensional checks.

Code

#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;
}

Results

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
coatless
  • 20,011
  • 13
  • 69
  • 84
2

I have used sugar functions Rcpp::cbind and Rcpp::transpose.

The code:

#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;
}

And we receive:

>   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
AgnieszkaTomczyk
  • 253
  • 2
  • 12