如何使用 Rcpp 创建带有属性的列表

How to create a list with attributes with Rcpp

是否可以使用 Rcpp 创建带有属性的列表?如果是,怎么做?

我需要这样一个用于 shinyTree 包的列表,它需要这个结构并且我的 R 代码非常慢,因为我需要几个嵌套循环来遍历所有列表级别。

这是我需要的结构:

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"

首先,使用 Rcpp::List::create() 创建列表。 使用 Rcpp::Named("NameHere") = data 添加单个命名条目。 然后使用 my_list.attr("attribute-name") = attribute_val.

添加附加标记

这是由:

#include<Rcpp.h>

// [[Rcpp::export]]
Rcpp::List create_list_with_attr(Rcpp::CharacterVector x) {
    Rcpp::List val = Rcpp::List::create(
        Rcpp::Named("Name1") = x
    );

    val.attr("type") = "root";
    val.attr("sticon") = "fa-icon";
    val.attr("stclass") = "color";

    return val;
}

从那里,我们可以测试它:

create_list_with_attr(" ")
# $Name1
# [1] " "
#
# attr(,"type")
# [1] "root"
# attr(,"sticon")
# [1] "fa-icon"
# attr(,"stclass")
# [1] "color"

有关更多示例,请参阅 Rcpp Gallery,但这里有一个快速示例:

代码

#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()
*/

输出

R> Rcpp::sourceCpp("~/git/Whosebug/54693381/answer.cpp")

R> quickdemo()
$Name1
[1] ""
attr(,"type")
[1] "root"
attr(,"sticon")
[1] "fa-icon"
attr(,"stclass")
[1] "color"

R>