vkubicki
vkubicki

Reputation: 1124

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 ?

Upvotes: 0

Views: 152

Answers (2)

theogrost
theogrost

Reputation: 21

This works:

// [[Rcpp::export]]
void modifyList(List& l, std::string i) {
  l[i]= "x";
}

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

and gives:

> rcppTest()
$`a`
[1] "x"

The problem is you are trying to:

error: invalid initialization of non-const reference of type 'Rcpp::List& {aka Rcpp::Vector<19>&}'

Upvotes: 0

coatless
coatless

Reputation: 20746

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"

Upvotes: 3

Related Questions