# [Rcpp-devel] Mimicing of X[ X[,col]==val, ] with RcppArmadillo

Søren Højsgaard sorenh at math.aau.dk
Thu May 31 15:07:16 CEST 2012

```Dear List

I've tried to make an Rcpp version of X[ X[,col]==val, ] and came up with the following:

sqbr <- cxxfunction(signature(r_X='float', r_col='int', r_val='double'), body =
'
using namespace arma;
using namespace Rcpp;
using namespace std;

mat XX     = as<mat>(r_X);
double val = as_scalar(as<fvec>(r_val));

colvec col = XX.cols(as<uvec>(r_col)-1);
vec valvec = val * ones<vec>(XX.n_rows,1);

NumericVector valvec2 = wrap(valvec), col2 = wrap(col);
LogicalVector rowbool = valvec2 == col2;

uvec rowidx = find(as<uvec>(rowbool)>0);

Rcout << col;  Rcout << valvec;
Rcout << "rowbool" << endl << as<uvec>(rowbool); Rcout << "rowidx" << endl << rowidx;

mat ans = XX.rows(rowidx);
return(wrap(ans));
'

X <- matrix(c(1,2,3,4,4,5,6,7,7),nr=3)
cc <- 2
vv <- 4
sqbr(X,cc,vv)

I would expect that there is a way of doing this without having to jump "into" armadillo "back" to Rcpp and "into" Armadillo again. I just can't spot an easier way. If a simpler solution exists I would be interested to know...

A related question. Suppose I want to do X[ X[,col1]==val & X[,col2]>val2, ]. Is there any elegant way of doing this. I am thinking whether the operators "==" and ">" can be passed on as arguments so that one can do something similar to
> `>`(5,2)
[1] TRUE
> `==`(5,2)
[1] FALSE

Best regards
Søren
```