Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using colon (':') to access elements in an array in C++ (in Rcpp)

Tags:

c++

r

rcpp

I am trying to run the following code. Frankly I know C++ only little but I want to get the following function run. Can you help me run this silly example?

cppFunction(
  'NumericVector abc(int x, int x_end, NumericVector y)
  {
    NumericVector z;
    int x1 = x + x_end;
    z = y[x:x1];
    return(z);  
   }'
)

abc(3,c(0,1,10,100,1000,10000))

I see this ...

error: expected ']' before ':' token

Update Sorry I forgot to mention that I need to generate a sequence of numbers from x to x1. The function IntegerVector::create only creates a variable with only x and x1 not x though x1. The example I gave was trivial. I updated the example now. I need to do in C++ what seq() does in R

Solution based on the answer below (@SleuthEye)

Rcpp::cppFunction(
  'NumericVector abc(int x, int x_end, NumericVector y)
  {
  NumericVector z;
  Range idx(x,x_end);
  z = y[idx];
  return(z);  
  }'
)

abc(3,5,c(0,1,10,100,1000,10000))
[1]   100  1000 10000
like image 926
Stat-R Avatar asked May 05 '15 21:05

Stat-R


People also ask

Which is the best way to access elements in an array?

Array elements are accessed by using an integer index.

Which keyword is used to access the elements of array in C?

Elements of an array are accessed by specifying the index ( offset ) of the desired element within square [ ] brackets after the array name.


1 Answers

The code argument to Rcpp's cppFunction must include valid C++ code. The library tries to make as seamless as possible, but is still restricted to the syntax of C++. More specifically, C++ does not have a range operator (:) and correspondingly the C++ compiler tells you that the indexing expression must be a valid index (enclosed within [], without the :). The type of the index could be an int or IntegerVector, but it cannot contain the : character.

As suggesting in Rcpp subsetting article, you may however create a vector which represent the desired (x,x+1) range which you can then use to index NumericVector variables as such:

IntegerVector idx = IntegerVector::create(x, x+1);
z = y[idx];

More generally, you can use a Range in a similar fashion:

Range idx(x, x1);
z = y[idx];
like image 138
SleuthEye Avatar answered Nov 14 '22 21:11

SleuthEye