是否可以使用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 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/stackoverflow/54693381/answer.cpp")
R> quickdemo()
$Name1
[1] ""
attr(,"type")
[1] "root"
attr(,"sticon")
[1] "fa-icon"
attr(,"stclass")
[1] "color"
R>
首先,使用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"