I am trying to translate a piece of R code to C++ (via Rcpp) that uses the %in%
operator. I know Rcpp has a sugar in()
, but I don't understand how it relates. There is another SO question regarding %in%
but I couldn't sort out how that one relates too. The Rcpp gallery is wonderful but when I search in()
I don't find any posts.
Here is a simple example of the problem. Suppose you want to create an identity matrix but constrain some elements on the diagonal to be zero. (This is obviously no longer an identity matrix but you understand what I mean.) You can do it in R with a function like this:
r_eye <- function(n, v) {
A <- matrix(data = 0, nrow = n, ncol = n)
for(i in 1:n) {
for(j in 1:n) {
if(i==j & !(i %in% v)) {
A[i,j] <- 1
}
}
}
return(A)
}
where n
is an integer that determines the size of the square matrix and v
is a integer vector of "constraints". Starting with a matrix of zeros, you loop over rows and columns. If row equals column, and if row is not among the constraints, assign the value one to the matrix entry. For instance, if you run r_eye(n=6, v=c(1,2,3))
, you get an "identity" matrix where the first three diagonal elements are zero and the remaining are one:
> r_eye(n = 6, v = c(1,2,3))
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 0 0 0 0 0
[2,] 0 0 0 0 0 0
[3,] 0 0 0 0 0 0
[4,] 0 0 0 1 0 0
[5,] 0 0 0 0 1 0
[6,] 0 0 0 0 0 1
The bottleneck to translating this to C++ is the second part of the "if" condition: !(i %in% v)
. I can create an identity matrix with
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix cpp_eye(int n) {
NumericMatrix A(n,n);
for(int i = 0; i <= n; i++) {
for(int j = 0; j <= n; j++) {
if(i==j) {
A(i,j) = 1;
}
}
}
return A;
}
but is it possible to squeeze in that second "if" condition like the R function does? Or do I have to consider a different approach?