I am puzzled.
The following compile and work fine:
#include
using namespace Rcpp;
// [[Rcpp::export]]
List test(){
List l;
Integer
It is because of this line:
l[0][1] = 1;
The compiler has no idea that l
is a list of integer vectors. In essence l[0]
gives you a SEXP
(the generic type for all R objects), and SEXP
is an opaque pointer to SEXPREC
of which we don't have access to te definition (hence opaque). So when you do the [1]
, you attempt to get the second SEXPREC
and so the opacity makes it impossible, and it is not what you wanted anyway.
You have to be specific that you are extracting an IntegerVector
, so you can do something like this:
as(l[0])[1] = 1;
or
v[1] = 1 ;
or
IntegerVector x = l[0] ; x[1] = 1 ;
All of these options work on the same underlying data structure.
Alternatively, if you really wanted the syntax l[0][1]
you could define your own data structure expressing "list of integer vectors". Here is a sketch:
template
class ListOf {
public:
ListOf( List data_) : data(data_){}
T operator[](int i){
return as( data[i] ) ;
}
operator List(){ return data ; }
private:
List data ;
} ;
Which you can use, e.g. like this:
// [[Rcpp::export]]
List test2(){
ListOf l = List::create( IntegerVector(5, NA_INTEGER) ) ;
l[0][1] = 1 ;
return l;
}
Also note that using .push_back
on Rcpp
vectors (including lists) requires a complete copy of the list data, which can cause slow you down. Only use resizing functions when you don't have a choice.