1

I have an R nested-list object (called Rlist) containing 300 elements, each of which contains an "inner-list" containing anywhere from 1-100 elements. I want to pass Rlist to a function I'm writing in Rcpp, but I'm having trouble figuring out how to extract the inner-lists within Rcpp.

How can I pass Rlist to my Rcpp function? In particular, suppose I want to access all elements within the 10th inner-list object. How can I do this? I tried passing Rlist to Rcpp as a "List" object, and then tried Rlist(9) but this is not giving me what I want.

Thanks

bayes003
  • 121
  • 2
  • 1
    When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 07 '18 at 20:08

1 Answers1

6

There is no magic. Just use list access methods to, well, access lists.

Code

#include <Rcpp.h>

// [[Rcpp::export]]
double accessLOL(Rcpp::List l) {
  Rcpp::List l2 = l["outer"];
  Rcpp::List l3 = l2["middle"];
  Rcpp::List l4 = l3["inner"];
  return l4["value"];
}

/*** R
li <- list(value=42)
lm <- list(inner=li)
lo <- list(middle=lm)
l <- list(outer=lo)
accessLOL(l)
*/

Demo

R> Rcpp::sourceCpp("/tmp/lolol.cpp")

R> li <- list(value=42)

R> lm <- list(inner=li)

R> lo <- list(middle=lm)

R> l <- list(outer=lo)

R> accessLOL(l)
[1] 42
R> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725