[Rcpp-devel] add new components to list without specifying list size initially

Walrus Foolhill walrus.foolhill at gmail.com
Thu Aug 11 10:06:25 CEST 2011


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");
for(int i=0; i<2; ++i){
  mylist.add(names[i], IntegerVector::create());
  mylist[names[i]].push_back(i);
}
return mylist;

Do you know how I could achieve this? Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20110811/2fdb9a09/attachment.htm>


More information about the Rcpp-devel mailing list