嗨,我正在尝试将 Rcpp 的数字向量切片为元素 2 到 101
在 R 中,我会这样做:
array[2:101]
如何在 RCpp 中执行相同的操作?
我试着看这里:http://gallery.rcpp.org/articles/subsetting/但是资源有一个示例,它列出了使用 IntegerVector::create(( 的所有元素。但是,::create(( 受到元素数量的限制。(除了乏味(。有什么方法可以在给定 2 个索引的情况下对向量进行切片?
这
可以通过 Rcpp 的Range
函数来实现。这将生成等效C++位置索引序列。例如
Rcpp::Range(0, 3)
会给出:
0 1 2 3
注意:C++指数从 0 开始,而不是从 1 开始!
例:
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericVector subset_range(Rcpp::NumericVector x,
int start = 1, int end = 100) {
// Use the Range function to create a positional index sequence
return x[Rcpp::Range(start, end)];
}
/***R
x = rnorm(101)
# Note: C++ indices start at 0 not 1!
all.equal(x[2:101], subset_range(x, 1, 100))
*/