创建具有20个以上元素的NumericVector会导致错误消息.这与本文件(最底层)一致:http://statr.me/rcpp-note/api/Vector_funs.html
目前,我公开了一个类(使用RCPP_MODULE),其中一个方法返回所需的NumericVector.我怎样才能返回超过20个元素?
#include <Rcpp.h>
class nvt {
public:
nvt(int x, double y) {...}
NumericVector run(void) {
....
return NumericVector::create(_["a"]=1,_["b"]=2, .....,_["c"]=21);
}
};
RCPP_MODULE(nvt_module){
class_<nvt>("nvt")
.constructor<int,double>("some description")
.method("run", &nvt::run,"some description")
;
}
Run Code Online (Sandbox Code Playgroud)
创建具有所需大小的向量,然后分配值和名称.这是一个Rcpp"内联"函数(人们更容易尝试它),但它可以在你的上下文中工作:
library(Rcpp)
library(inline)
big_vec <- rcpp(body="
NumericVector run(26);
CharacterVector run_names(26);
# make up some data
for (int i=0; i<26; i++) { run[i] = i+1; };
# make up some names
for (int i=0; i<26; i++) { run_names[i] = std::string(1, (char)('A'+i)); };
run.names() = run_names;
return(run);
")
big_vec()
## A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Run Code Online (Sandbox Code Playgroud)
Bob已经向您展示了a)您错误地将宏定义create()
帮助器上的约束绑定到了绑定,以及b)如何通过内联包和循环执行此操作.
这是使用Rcpp Attribute的替代解决方案.将以下内容复制到文件中,例如/tmp/named.cpp
:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector makevec(CharacterVector nm) {
NumericVector v(nm.size());
v = Range(1, nm.size());
v.attr("names") = nm;
return v;
}
/*** R
makevec(LETTERS)
makevec(letters[1:10])
*/
Run Code Online (Sandbox Code Playgroud)
简单地调用sourceCpp("/tmp/named.cpp")
将编译,链接,加载并执行底部的R插图:
R> sourceCpp("/tmp/named.cpp")
R> makevec(LETTERS)
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
R> makevec(letters[1:10])
a b c d e f g h i j
1 2 3 4 5 6 7 8 9 10
R>
Run Code Online (Sandbox Code Playgroud)