通过引用修改单独函数中 Rcpp::List 的小节
Modifying a subsection of an Rcpp::List in a Separate Function by Reference
我希望能够通过函数修改 Rcpp::List
的子部分。由于 Rcpp::List
是指向某些 R 数据的指针,我认为可以这样做:
void modifyList(Rcpp::List l) {
l["x"] = "x";
}
// [[Rcpp::export]]
Rcpp::List rcppTest() {
Rcpp::List res;
res["a"] = Rcpp::List::create();
modifyList(res["a"]);
return res;
}
我希望得到 return 值为 rcppTest
的列表,其元素 "x" 的值为 "x"。然而,returned 列表是空的。
如果我改用签名 modifyList(Rcpp::List& l)
,我会收到编译错误
rcppTest.cpp:17:6: note: candidate function not viable: no known conversion from 'Rcpp::Vector<19, PreserveStorage>::NameProxy' (aka 'generic_name_proxy<19, PreserveStorage>') to 'Rcpp::List &' (aka 'Vector<19> &') for 1st argument
如何通过函数修改 Rcpp::List
的子部分?
简而言之,无法通过引用修改列表。在这种情况下,您 必须 return Rcpp::List
正如@RalfStubner 从评论中指出的那样。
例如
#include<Rcpp.h>
// Specified return type of List
Rcpp::List modifyList(Rcpp::List l) {
l["x"] = "x";
return l;
}
// [[Rcpp::export]]
Rcpp::List rcppTest() {
Rcpp::List res;
res["a"] = Rcpp::List::create();
// Store result back into "a"
res["a"] = modifyList(res["a"]);
return res;
}
测试:
rcppTest()
# $a
# $a$x
# [1] "x"
这个有效:
// [[Rcpp::export]]
void modifyList(List& l, std::string i) {
l[i]= "x";
}
// [[Rcpp::export]]
Rcpp::List rcppTest() {
Rcpp::List res;
res["a"] = Rcpp::List::create();
modifyList(res,"a");
return res;
}
并给出:
> rcppTest()
$`a`
[1] "x"
问题是您正在尝试:
error: invalid initialization of non-const reference of type 'Rcpp::List& {aka Rcpp::Vector<19>&}'
我希望能够通过函数修改 Rcpp::List
的子部分。由于 Rcpp::List
是指向某些 R 数据的指针,我认为可以这样做:
void modifyList(Rcpp::List l) {
l["x"] = "x";
}
// [[Rcpp::export]]
Rcpp::List rcppTest() {
Rcpp::List res;
res["a"] = Rcpp::List::create();
modifyList(res["a"]);
return res;
}
我希望得到 return 值为 rcppTest
的列表,其元素 "x" 的值为 "x"。然而,returned 列表是空的。
如果我改用签名 modifyList(Rcpp::List& l)
,我会收到编译错误
rcppTest.cpp:17:6: note: candidate function not viable: no known conversion from 'Rcpp::Vector<19, PreserveStorage>::NameProxy' (aka 'generic_name_proxy<19, PreserveStorage>') to 'Rcpp::List &' (aka 'Vector<19> &') for 1st argument
如何通过函数修改 Rcpp::List
的子部分?
简而言之,无法通过引用修改列表。在这种情况下,您 必须 return Rcpp::List
正如@RalfStubner 从评论中指出的那样。
例如
#include<Rcpp.h>
// Specified return type of List
Rcpp::List modifyList(Rcpp::List l) {
l["x"] = "x";
return l;
}
// [[Rcpp::export]]
Rcpp::List rcppTest() {
Rcpp::List res;
res["a"] = Rcpp::List::create();
// Store result back into "a"
res["a"] = modifyList(res["a"]);
return res;
}
测试:
rcppTest()
# $a
# $a$x
# [1] "x"
这个有效:
// [[Rcpp::export]]
void modifyList(List& l, std::string i) {
l[i]= "x";
}
// [[Rcpp::export]]
Rcpp::List rcppTest() {
Rcpp::List res;
res["a"] = Rcpp::List::create();
modifyList(res,"a");
return res;
}
并给出:
> rcppTest()
$`a`
[1] "x"
问题是您正在尝试:
error: invalid initialization of non-const reference of type 'Rcpp::List& {aka Rcpp::Vector<19>&}'