0

I try to translate some R code into RcppArmadillo and therefore I would also like to do the following:

Assume there is a nonnegative vector v and a matrix M, both with for example m rows. I would like to get rid of all rows in the matrix M whenever there is a zero in the corresponding row of the vector v and afterwards also get rid of all entries that are zero in the vector v. Using R this is simply just the following:

M = M[v>0,]

v = v[v>0] 

So my question is if there is a way to do this in RcppArmadillo. Since I am quite new to any programming language I was not able to find anything that could solve my problem, although I think that I am not the first one who asks this maybe quite easy question.

coatless
  • 20,011
  • 13
  • 69
  • 84
Cello
  • 91
  • 4

1 Answers1

5

Of course there is a way to go about subsetting elements in both Rcpp (subsetting with Rcpp) and RcppArmadillo (Armadillo subsetting).

Here is a way to replicate the behavior of R subsets in Armadillo.

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;

// Isolate by Row
// [[Rcpp::export]]
arma::mat vec_subset_mat(const arma::mat& x, const arma::uvec& idx) {
  return x.rows(find(idx > 0));
}

// Isolate by Element
// [[Rcpp::export]]
arma::vec subset_vec(const arma::vec& x) {
  return x.elem(find(x > 0));
}

/*** R
set.seed(1334)
m = matrix(rnorm(100), 10, 10)
v = sample(0:1, 10, replace = T)

all.equal(m[v>0,], vec_subset_mat(m,v))
all.equal(v[v>0], as.numeric(subset_vec(v)))
*/
coatless
  • 20,011
  • 13
  • 69
  • 84
  • I am grateful to @coatless for tirelessly answering this here but it really is a duplicate question as I too have referenced the Rcpp Gallery on this a few times ... – Dirk Eddelbuettel Apr 12 '16 at 16:41