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
Array elements are accessed by using an integer index.
Elements of an array are accessed by specifying the index ( offset ) of the desired element within square [ ] brackets after the array name.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With