Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to slice Rcpp NumericVector for elements 2 to 101?

Tags:

rcpp

Hi I'm trying to slice Rcpp's NumericVector for elements 2 to 101

in R, I would do this:

array[2:101]

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?

like image 570
Alexander Avatar asked Nov 12 '17 06:11

Alexander


1 Answers

This is possible with Rcpp's Range function. This generates the equivalent C++ positional index sequence. e.g.

Rcpp::Range(0, 3)

would give:

0 1 2 3

Note: C++ indices begin at 0 not 1!

Example:

#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))
*/
like image 190
coatless Avatar answered Sep 28 '22 10:09

coatless