Reputation: 71
I'm currently porting some R code into Rcpp for a speed improvement (which has been successful so far), but I'm trying to understand why Rcpp doesn't allow certain types of assignment when it comes to subsetting.
For example, in R if I have three vectors A, B, C, and if for some condition of C i want to fill A with the values of B, then i can write:
A[C < 3] = B[C< 3]
However I get an error when i try something similar in Rcpp.
Rccp seems to be happy to assign things like:
A[C < 3] = X
...and...
Y = B[C< 3]
...but not...
A[C < 3] = B[C< 3]
Therefore I first assign the RHS to another vector first, and then assign that vector to the LHS, it works fine!?
Here is some example code that works:
cppFunction("
NumericVector valuesOverThree(NumericVector b){
NumericVector a(b.size());
NumericVector temp = b[b > 3];
a[b > 3] = temp;
return a;
}
")
valuesOverThree(1:6)
# returns: [0, 0, 0, 4, 5, 6]
And here is some that gives an error:
cppFunction("
NumericVector valuesOverThree(NumericVector b){
NumericVector a(b.size());
a[b > 3] = b[b > 3];
return a;
}
")
valuesOverThree(1:6)
# returns: error message
Is there any reason for this, or anyway I can make this work on one line?
As shown, there is a workaround, but it would be nicer if i could write everything on one line.
Many thanks
Upvotes: 3
Views: 668
Reputation: 522
Just a simple remainder.
You can do exactly what you want with latest Rcpp.
> cppFunction("
+ NumericVector valuesOverThree(NumericVector b){
+ NumericVector a(b.size());
+
+ a[b > 3] = b[b > 3];
+ return a;
+ }
+ ")
> valuesOverThree(1:6)
[1] 0 0 0 4 5 6
>
Upvotes: 1
Reputation: 368231
We have a Rcpp Gallery article on indexing / subsetting.
I have in the past used RcppArmadillo, there is also an Rcpp Gallery post besides the normal (and excellent) Armadillo documentation.
I also would not worry too much about getting everything onto one line. The compiler is pretty good at removing temporaries. Rather, I try to write code I can still read in a week.
Upvotes: 2