Search code examples
rrcpp

How to create a list with attributes with Rcpp


Is it possible to create a list with attributes with Rcpp? And if so, how?

I need such a list for the shinyTree package, which requires this structure and my R code is quite slow, as I need several nested loops to go through all the list-levels.

This is the structure I need:

list(Name1 = structure("", type = "root", sticon = "fa-icon", stclass = "color"))
$Name1
[1] ""
attr(,"type")
[1] "root"
attr(,"sticon")
[1] "fa-icon"
attr(,"stclass")
[1] "color"

Solution

  • See the Rcpp Gallery for more examples, but here is a quick one:

    Code

    #include <Rcpp.h>
    
    // [[Rcpp::export]]
    Rcpp::List quickdemo() {
      Rcpp::CharacterVector v = Rcpp::CharacterVector::create("");
      v.attr("type") = "root";
      v.attr("sticon") = "fa-icon";
      v.attr("stclass") = "color";
      return Rcpp::List::create(Rcpp::Named("Name1") = v);
    }
    
    /*** R
    quickdemo()
    */
    

    Output

    R> Rcpp::sourceCpp("~/git/stackoverflow/54693381/answer.cpp")
    
    R> quickdemo()
    $Name1
    [1] ""
    attr(,"type")
    [1] "root"
    attr(,"sticon")
    [1] "fa-icon"
    attr(,"stclass")
    [1] "color"
    
    R>