Kevin Ushey — written Mar 16, 2014 — source
Rcpp 0.11.1 has introduced flexible subsetting for Rcpp vectors. Subsetting is
implemented for the Rcpp vector types through the [
operator, and intends to
mimic R’s [
operator for most cases.
We diverge from R’s subsetting semantics in a few important ways:
For integer and numeric vectors, 0-based indexing is performed, rather than 1-based indexing, for subsets.
We throw an error if an index is out of bounds, rather than returning an
NA
value,
We require logical subsetting to be with vectors of the same length, thus avoiding bugs that can occur when a logical vector is recycled for a subset operation.
Some examples are showcased below:
[1] 1 2 3 4 5
[[1]] [1] 1 [[2]] [1] 2 [[3]] [1] 3
$a [1] 1 $e [1] 5 $g [1] 7
Most excitingly, the subset mechanism is quite flexible and works well with Rcpp sugar. For example:
[1] -0.56048 -0.23018 0.07051 0.12929
[1] 1 2 4 10
[[1]] [1] "a" [[2]] [1] "b"
And, these can be quite fast:
[1] TRUE
Unit: milliseconds expr min lq median uq max neval R_in_range(x, -1, 1) 8.168 8.556 9.02 9.073 9.223 5 in_range(x, -1, 1) 5.210 5.424 5.48 5.507 6.233 5
[1] TRUE
Unit: milliseconds expr min lq median uq max neval R_no_na(x) 3.958 3.960 4.019 4.02 4.458 5 no_na(x) 1.891 1.936 1.961 2.02 2.755 5
We hope users of Rcpp will find the new subset semantics fast, flexible, and useful throughout their projects.
Tweet