0

I am creating a library to draw samples from a bayesian model, as a backend for an R package. Thing is, MCMC algorithms tend to give a difficult time debugging. Moreover, Rcpp does not have an easy way to debug; in practice I ended up with a massive amount of "cout" statements.

The issue is when I tried to move everything to a standalone library, I realized I fell in love with Rcpp's List. Is a really neat way to store samples with different dimensions. I tried to understand Rcpp's implementation but sincerely I could not comprehend it (which is based on policies) to try to replicate it.

The question: Is there any way to implement an arbitrary sized, named tuple? (in a broad sense, not necessary using C++ tuples).

I know I could link Rcpp using the R install path, but I'm not sure if this could be a good practice or if I will have problems trying to upload the R package to CRAN (they are very strict) or using it as a standalone library for users not having R.

Thanks!

  • use `boost::any`? [examples](https://www.boost.org/doc/libs/1_61_0/doc/html/any/s02.html) – eddi Jun 04 '18 at 21:49
  • Oh, looks promising. But I kind of need the "named" part (question edited). Maybe adding a lookup table to a custom object and overloading the "[" operator could do the trick, but I don't know in advance (I learned C a long time ago, but I am new to C++ in general). What do you think? – Daniel León Jun 04 '18 at 21:59
  • You can do whatever pleases inside C++, but recall that when you want to come back to R, you _must_ pass via the `SEXP .Call(....)` interface. Rcpp helps and maps a lot of what _can be mapped_ but for other things _you_ may have to write the mapper. – Dirk Eddelbuettel Jun 04 '18 at 22:04
  • That seems reasonable. I don't know if CRAN supports compiling code with C++17 (for the `std::any`)`, but I suppose I could replace it with `boost::any`. Thanks! – Daniel León Jun 04 '18 at 22:05
  • That is documented, and generally "no". C++14 is possible but a stretch. So stick with `boost::any` for the time being. – Dirk Eddelbuettel Jun 04 '18 at 22:06
  • In addition to `boost::any`, you can also use `boost::variant` (e.g., `boost::variant`) or the recursive variant if you need a nested structure. But it sounds like you are looking for something simpler like `vector< map >`. – thc Jun 04 '18 at 22:38
  • @DirkEddelbuettel Yes! I will wrap up everything with Rcpp + RcppArmadillo to ease the integration with R. – Daniel León Jun 04 '18 at 22:49

1 Answers1

0

I am not sure this is what you want. If you want to build a list with arbitrary size in Rcpp and return to R side, you can try something like below:

std::vector<std::string> names;

std::vector<SEXP> elements;

// do something with the elements and names

Rcpp::List result(elements.size());

for (size_t i = 0; i < elements.size(); ++i) {
    result[i] = elements[i];
}

result.attr("names") = Rcpp::wrap(names);
// result can be return to R as a list
Qiang Kou
  • 522
  • 4
  • 8