[Rcpp-devel] Rcpp::List lost attributes after updating elements

Dirk Eddelbuettel edd at debian.org
Sun Dec 9 20:25:09 CET 2012

On 9 December 2012 at 14:07, Jiqiang Guo wrote:
| Note in the above, the printout for the second does not print any attribute as
| for the first function. 

Hm. That it not desirable so maybe we can do better, but you should also note
that you are using the list type in a suboptimal way by growing piece by
piece which leads to __copies__ being made at which point we may cast to
vector and drop the attributes. 

Here is a ever-so-slightlt modified example that works:

#include <Rcpp.h>

// [[Rcpp::export]]
SEXP crtlist3() {
    Rcpp::List lst(2);   // reserve known size
    lst[0] = 10;
    lst.attr("att1") = 1;
    lst[1] = 20;
    return lst;

R> sourceCpp("/tmp/jiqiang.cpp")
R> crtlist3()
[1] 10

[1] 20

[1] 1

Essentially I do two things differently:  reserve the needed size, and index
by position.  The attr then remains.


Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com  

More information about the Rcpp-devel mailing list