使用冒号(':')访问C++中的数组元素(在Rcpp中)

Sta*_*t-R 5 c++ r rcpp

我试图运行以下代码.坦率地说我只知道C++很少,但我希望运行以下函数.你能帮助我运行这个愚蠢的例子吗?

cppFunction(
  'NumericVector abc(int x, int x_end, NumericVector y)
  {
    NumericVector z;
    int x1 = x + x_end;
    z = y[x:x1];
    return(z);  
   }'
)

abc(3,c(0,1,10,100,1000,10000))
Run Code Online (Sandbox Code Playgroud)

我明白了......

错误:在':'标记之前预期']'

更新 对不起,我忘了提,我需要从生成数字的序列xx1.该功能IntegerVector::create只与只创建一个变量xx1不是x虽然x1.我给出的例子是微不足道的.我现在更新了这个例子.我需要在C++中做什么seq()R中

解决方案基于以下答案(@SleuthEye)

Rcpp::cppFunction(
  'NumericVector abc(int x, int x_end, NumericVector y)
  {
  NumericVector z;
  Range idx(x,x_end);
  z = y[idx];
  return(z);  
  }'
)

abc(3,5,c(0,1,10,100,1000,10000))
[1]   100  1000 10000
Run Code Online (Sandbox Code Playgroud)

Sle*_*Eye 7

Rcpp's 的代码参数cppFunction必须包含有效的C++代码.该库试图尽可能无缝地进行,但仍然受限于C++的语法.更具体地说,C++没有范围运算符(:),相应地,C++编译器告诉您索引表达式必须是有效索引(包含在其中[],没有:).索引的类型可以是intIntegerVector,但不能包含该:字符.

正如在Rcpp子集化文章中建议的那样,您可以创建一个表示所需(x,x+1)范围的向量,然后您可以使用该向量来索引NumericVector变量:

IntegerVector idx = IntegerVector::create(x, x+1);
z = y[idx];
Run Code Online (Sandbox Code Playgroud)

更一般地说,您可以Range以类似的方式使用a :

Range idx(x, x1);
z = y[idx];
Run Code Online (Sandbox Code Playgroud)