[Rcpp-devel] add new components to list without specifying list size initially
Dirk Eddelbuettel
edd at debian.org
Thu Aug 11 14:00:34 CEST 2011
On 11 August 2011 at 03:06, Walrus Foolhill wrote:
| Hello,
| I need to create a list and then fill it sequentially by adding components in a
| for loop. Here is an example that works:
|
| library(inline)
| src <- '
| Rcpp::List mylist(2);
| for(int i=0; i<2; ++i)
| mylist[i] = i;
| mylist.names() = CharacterVector::create("a","b");
| return mylist;
| '
| fun <- cxxfunction(body=src, plugin="Rcpp")
| print(fun())
|
| But what I really want is to create an empty list and then fill it, that is
| without specifying its number of components before hand... This is because I
| don't know in advance at which step of the for loop I will need to create a new
| component. Here is an example, that obviously doesn't work, but that should
| show what I am looking for:
|
| Rcpp::List mylist;
| CharacterVector names = CharacterVector::create("a", "b");
If you know how long names is, you know how long mylist going to be ....
| for(int i=0; i<2; ++i){
| mylist.add(names[i], IntegerVector::create());
| mylist[names[i]].push_back(i);
I don't understand what that is trying to do.
| }
| return mylist;
|
| Do you know how I could achieve this? Thanks.
Rcpp::List is an alias for Rcpp::GenericVector, and derives from Vector. You
can look at the public member functions -- there are things like
push_back()
push_front()
insert()
etc that behave like STL functions __but are inefficient as we (almost
always) need to copy the whole object__ so they are not recommended.
When I had to deal with 'unknown quantities of data' returning I was mostly
able to either turn it into a 'fixed or known columns, unknow rows' problem
(easy, just grow row-wise) or I 'cached' in a C++ data structure first before
returning to R via Rcpp structures -- and then I knew the dimensions for the
to-be-created object too.
Dirk
--
Two new Rcpp master classes for R and C++ integration scheduled for
New York (Sep 24) and San Francisco (Oct 8), more details are at
http://dirk.eddelbuettel.com/blog/2011/08/04#rcpp_classes_2011-09_and_2011-10
More information about the Rcpp-devel
mailing list