Skip to content

[Rcpp-devel] Subsetting / slicing with Vectors

2 messages · Kevin Ushey, Dirk Eddelbuettel

#
Hi guys,

I'm wondering -- what operations are available for subsetting of Vectors in
Rcpp? I've scoured through all the vignettes but it seems like a couple
'nice-to-haves' aren't there yet. My questions:

* is there a difference between subsetting a vector with () vs []?

* is it possible to subset based on a collection of indices, eg:

NumericVector X(10);
NumericVector Y = X[ c(1, 2, 5) ]

* is it possible to slice a vector, eg. such that we either hold a
reference to, or copy out, the elements at every 'x' indices? I know 'seq'
is available for consecutive indices, but might there be a third 'by'
argument coming, or an alternative function, soon?

Thanks for the help,
-Kevin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130112/b909a268/attachment.html>
#
Hi Kevin,
On 12 January 2013 at 11:10, Kevin Ushey wrote:
| I'm wondering -- what operations are available for subsetting of Vectors in
| Rcpp? I've scoured through all the vignettes but it seems like a couple
| 'nice-to-haves' aren't there yet. My questions:
| 
| * is there a difference between subsetting a vector with () vs []??

For vectors, both work. We sometimes wondered if one should test or not. I
think they both have the same speed.  It may be better to use () because ...

For matrices, [] does not work (C interview question: what is [3,4] returning ?)
so it may be better to get used to (i,j) anyway.
 
| * is it possible to subset based on a collection of indices, eg:
| 
| NumericVector X(10);
| NumericVector Y = X[ c(1, 2, 5) ]

Nope. "Not yet." May take a long time.

This came up before on StackOverflow where I once answered by pointing to an
RcppArmadillo solution as Armadillo _can_ do this.
 
I recently came up with a cleverish way to approximate this using the STL,
and wrote piece a for the Rcpp Gallery on it, so see

   http://gallery.rcpp.org/articles/stl-transform-for-subsetting/

| * is it possible to slice a vector, eg. such that we either hold a reference
| to, or copy out, the elements at every 'x' indices? I know 'seq' is available
| for consecutive indices, but might there be a third 'by' argument coming, or an
| alternative function, soon?

Nope. As we wrap around SEXPs which are contiguous vectors, I don't really
see how we can do this.
 
Hope this helps!

Dirk