[Rcpp-devel] Ranges and Casting

Dirk Eddelbuettel edd at debian.org
Wed Jan 6 07:10:48 CET 2021


Francisco,

On 5 January 2021 at 13:58, Francisco Bischoff wrote:
| First of all, let me thank all involved with the Rcpp package!
| 
| I just have a (maybe silly) question, but I struggle with this frequently
| in my codes:
| 
| Range() vs IntegerVector
| 
| One example is when I need a reverse index, like R's 10:1, so I had to
| write my own function that returns an IntegerVector. But, to work I have to
| do this ugly code:
| 
|           IntegerVector dot_rev_idxs1 = ::seq((i - 1), beginidx);
|           IntegerVector dot_rev_idxs2 = ::seq((idx_nn - 1), (beginidx +
| idx_diff));
|           IntegerVector dot_rev_idxs3 = ::seq((i - 1 + window_size), (
| beginidx + window_size));
|           IntegerVector dot_rev_idxs4 = ::seq((idx_nn - 1 + window_size), (
| beginidx + idx_diff + window_size));
|           dotproduct[dot_rev_idxs1] = (NumericVector)((NumericVector)cumsum(
| data[dot_rev_idxs1] * data[dot_rev_idxs2] -
| 
| data[dot_rev_idxs3] * data[dot_rev_idxs4]) +
|                                                       dotproduct[i]);
| 
| I frequently have to cast the results with (NumericVector)...
| 
| This also happens using Range(). But there is a difference if I use Range()
| this way: my_vector[Range(0,10)]; or Range range = Range(0,
| 10); my_vector[range];
| 
| How is the proper way to deal with it?

I am not sure I fully understand what it is that you try to and what you are
struggling with.

Could you construct a small self-contained example?
 
| Other question: as<NumericVector() doesn't 'cast' right? Does it try to
| 'convert' formats?
| 
| And finally, I see that Matlab has a unique way to deal with ranges:
| 
| Ex.:
| 
| 1) (1:10) --> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
| 2) (10:1) --> returns a vector with size zero
| 3) (10:-1:1) --> 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
| 
| Range() shouldn't at least reproduce the R's counterpart and accept Range(10,1)
| == 10:1?

We could probably generalize seq() to count down from 'high' to 'low'. Pull
requests welcome...

Dirk

-- 
https://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org


More information about the Rcpp-devel mailing list