Search code examples
c++rrcpp

Modifying a subsection of an Rcpp::List in a Separate Function by Reference


I would like to be able, via a function, to modify a sub part of a Rcpp::List. Since Rcpp::List is a pointer to some R data, I thought it would be possible to do something like this:

void modifyList(Rcpp::List l) {
  l["x"] = "x";
}

// [[Rcpp::export]]
Rcpp::List rcppTest() {
  Rcpp::List res;
  res["a"] = Rcpp::List::create();
  modifyList(res["a"]);
  return res;
}

I expected to get as return value of rcppTest a list with an element "x" of value "x". The returned list is empty however.

If instead I use the signature modifyList(Rcpp::List& l), I get a compilation error

rcppTest.cpp:17:6: note: candidate function not viable: no known conversion from 'Rcpp::Vector<19, PreserveStorage>::NameProxy' (aka 'generic_name_proxy<19, PreserveStorage>') to 'Rcpp::List &' (aka 'Vector<19> &') for 1st argument

How can I modify a a sub part of an Rcpp::List via a function ?


Solution

  • In short, modifying a list by reference isn't possible. In this case, you must return the Rcpp::List as @RalfStubner points out from the comments.

    e.g.

    #include<Rcpp.h>
    
    // Specified return type of List
    Rcpp::List modifyList(Rcpp::List l) {
      l["x"] = "x";
      return l;
    }
    
    // [[Rcpp::export]]
    Rcpp::List rcppTest() {
      Rcpp::List res;
      res["a"] = Rcpp::List::create();
    
      // Store result back into "a"
      res["a"] = modifyList(res["a"]);
    
      return res;
    }
    

    Test:

    rcppTest()
    # $a
    # $a$x
    # [1] "x"