How create an Rcpp NumericVector with more than 20 entries?

梦想与她 提交于 2019-12-01 19:04:23

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

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.

Here is an alternate solution using Rcpp Attribute. Copy the following to a file, say, /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:

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> 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!