简体   繁体   English

如何创建一个包含 20 多个条目的 Rcpp NumericVector?

[英]How create an Rcpp NumericVector with more than 20 entries?

Creating a NumericVector with more than 20 elements leads to error messages.创建包含 20 多个元素的 NumericVector 会导致错误消息。 This is in agreement with this document (at the very bottom): http://statr.me/rcpp-note/api/Vector_funs.html这与本文档(在最底部)一致: http : //statr.me/rcpp-note/api/Vector_funs.html

Currently, I expose a class (using RCPP_MODULE) of which one of its methods returns the desired NumericVector.目前,我公开了一个类(使用 RCPP_MODULE),其中一个方法返回所需的 NumericVector。 How can I return more than 20 elements?如何返回超过 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")
 ;
}

Create the vector with the size you need then assign the values & names.创建具有您需要的大小的向量,然后分配值和名称。 This is an Rcpp "inline" function (easier for folks to try it out) but it'll work in your context:这是一个 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

Bob already showed you that a) you mistakenly took the constraint on the macro-defined create() helper to be binding, and b) how to do this via the inline package and loops. Bob 已经向您展示了 a) 您错误地将宏定义的create()助手上的约束约束为绑定,以及 b) 如何通过内联包和循环执行此操作。

Here is an alternate solution using Rcpp Attribute.这是使用 Rcpp 属性的替代解决方案。 Copy the following to a file, say, /tmp/named.cpp :将以下内容复制到一个文件中,例如/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])
*/

Simply calling sourceCpp("/tmp/named.cpp") will compile, link, load and also execute the R illustration at the bottom:只需调用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM