如何为元素 2 到 101 切片 Rcpp NumericVector?
How to slice Rcpp NumericVector for elements 2 to 101?
您好,我正在尝试为元素 2 到 101 分割 Rcpp 的 NumericVector
在 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))
*/
您好,我正在尝试为元素 2 到 101 分割 Rcpp 的 NumericVector
在 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))
*/