如何创建一个具有超过20个条目的Rcpp NumericVector?

4

创建超过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")
 ;
}
2个回答

5
创建您需要的大小向量,然后分配值和名称。这是一个 Rcpp 的 "inline" 函数(更容易让大家尝试一下),但它也适用于您的上下文:
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

5

Bob已经向您展示了:

  • a) 您错误地将宏定义create()助手的约束视为绑定
  • b) 如何通过内联包和循环来解决此问题。

这里是一种使用Rcpp属性的替代方案。将以下内容复制到一个文件中,例如:/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])
*/

只需调用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> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接