简体   繁体   中英

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 aa sub part of an Rcpp::List via a function ?

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.

eg

#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"

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>&}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM