如何创建一个包含 20 多个条目的 Rcpp NumericVector? [英] How create an Rcpp NumericVector with more than 20 entries?

查看:37
本文介绍了如何创建一个包含 20 多个条目的 Rcpp NumericVector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建包含 20 多个元素的 NumericVector 会导致错误消息.这与本文档(在最底部)一致:http://statr.me/rcpp-note/api/Vector_funs.html

Creating a NumericVector with more than 20 elements leads to error messages. This is in agreement with this document (at the very bottom): http://statr.me/rcpp-note/api/Vector_funs.html

目前,我公开了一个类(使用 RCPP_MODULE),其中一个方法返回所需的 NumericVector.如何返回超过 20 个元素?

Currently, I expose a class (using RCPP_MODULE) of which one of its methods returns the desired NumericVector. How can I return more than 20 elements?

#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")
 ;
}

推荐答案

创建具有所需大小的向量,然后分配值 &名称.这是一个 Rcpp内联"函数(人们更容易尝试)但它可以在您的上下文中工作:

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:

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

这篇关于如何创建一个包含 20 多个条目的 Rcpp NumericVector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆