如何为元素 2 到 101 切片 Rcpp NumericVector? [英] How to slice Rcpp NumericVector for elements 2 to 101?
问题描述
我正在尝试为元素 2 到 101 切片 Rcpp 的 NumericVector
Hi I'm trying to slice Rcpp's NumericVector for elements 2 to 101
在 R 中,我会这样做:
in R, I would do this:
array[2:101]
我如何在 RCpp 中做同样的事情?
How do I do the same in RCpp?
I tried looking here: http://gallery.rcpp.org/articles/subsetting/ But the resource has an example that lists all the elements using IntegerVector::create(). However, ::create() is limited by the number of elements. (in addition to being tedious). Any way to slice a vector given 2 indices?
推荐答案
这可以通过 Rcpp 的 Range
函数实现.这会生成等效的 C++ 位置索引序列.例如
This is possible with Rcpp's Range
function. This generates the equivalent C++ positional index sequence. e.g.
Rcpp::Range(0, 3)
会给:
0 1 2 3
注意:C++ 索引从 0 开始,而不是 1!
Note: C++ indices begin at 0 not 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!