Rcpp NumericMatrix - how to delete a row / column?

The initial question is when I study Rcpp data classes / structures: is there a member function to erase a row / column for an object of the Rcpp::NumericMatrix ? (Or other types of type **Matrix types - I assume this is a template class)?

 library(Rcpp) cppFunction(' NumericMatrix sub1 {NumericMatrix x, int& rowID, int& colID) { // let assume separate functions for rowID or colID // but for the example case here x.row(rowID).erase(); // ??? does this type of member function exist? x.col(colID).erase(); // ??? return x; }') 

If this type of member function does not exist, how about this?

 cppFunction('NumericMatrix row_erase (NumericMatrix& x, int& rowID) { // a similar function would exist for removing a column. NumericMatrix x2(Dimension(x.nrow()-1, x.ncol()); int iter = 0; // possibly make this a pointer? for (int i = 0; i < x.nrow(); i++) { if (i != rowID) { x2.row(iter) = x.row(i); iter++; } } return x2; }') 

Or perhaps we want to remove a row / column set:

 cppFunction('NumericMatrix row_erase (NumericMatrix& x, IntegerVector& rowID) { // a similar function would exist for removing a column. rowID = rowID.sort(); NumericMatrix x2(Dimension(x.nrow()- rowID.size(), x.ncol()); int iter = 0; // possibly make this a pointer? int del = 1; // to count deleted elements for (int i = 0; i < x.nrow(); i++) { if (i != rowID[del - 1]) x2.row(iter) = x.row(i); iter++; } else { del++; } } return x2; }') 
+7
c ++ rcpp
source share
2 answers

Yes, both of them work (fixing my typos above). I got a conversion error trying to replace int iter with Rcpp::NumericMatrix::iterator iter . Any fix for this?

Please note that we do not need row_erase(NumericMatrix& x, int& ref) , as this is a special case of row_erase(NumericMatrix& x, IntegerVector& ref) .

 NumericMatrix row_erase (NumericMatrix& x, IntegerVector& rowID) { rowID = rowID.sort(); NumericMatrix x2(Dimension(x.nrow()- rowID.size(), x.ncol())); int iter = 0; int del = 1; // to count deleted elements for (int i = 0; i < x.nrow(); i++) { if (i != rowID[del - 1]) { x2.row(iter) = x.row(i); iter++; } else { del++; } } return x2; } NumericMatrix col_erase (NumericMatrix& x, IntegerVector& colID) { colID = colID.sort(); NumericMatrix x2(Dimension(x.nrow(), x.ncol()- colID.size())); int iter = 0; int del = 1; for (int i = 0; i < x.ncol(); i++) { if (i != colID[del - 1]) { x2.col(iter) = x.column(i); iter++; } else { del++; } } return x2; } 
0
source share

How about using RcppArmadillo? I think the intent of the code will be much clearer ...

 #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] using namespace arma; // [[Rcpp::export]] mat sub1( mat x, uword e) { x.shed_col(e-1); x.shed_row(e-1); return x; } /*** R sub1( matrix(1:9,3), 2 ) */ 

 > sub1( matrix(1:9,3), 2 ) [,1] [,2] [1,] 1 7 [2,] 3 9 
+4
source share

All Articles