[Rcpp-devel] subsetting a matrix

Yixuan Qiu yixuan.qiu at cos.name
Tue Mar 4 02:13:57 CET 2014


Hi Hideyoshi,
You may try the code below:


cppFunction(depends = "RcppArmadillo",
        'NumericMatrix ss(NumericMatrix X_, IntegerVector ind_) {

             int n = X_.nrow(), k = X_.ncol();

             arma::mat X(X_.begin(), n, k, false);
             arma::uvec ind = as<arma::uvec>(ind_);
             arma::mat submat = X.rows(ind - 1);

             return wrap(submat);
         }')

m = matrix(rnorm(90), ncol=3);
ss(m, c(1, 5, 12, 22))



Best,
Yixuan


2014-03-03 19:24 GMT-05:00 Hideyoshi Maeda <hideyoshi.maeda at gmail.com>:

> Hi Rcpp-devel list,
>
> I would like to subset a matrix by only selecting certain rows.
>
> Something like the below...where y is a vector of integers that represent
> the rows to be selected. However the below does not seem to work.
>
> // [[Rcpp::export]]
> Rcpp::NumericMatrix ss(SEXP X_,SEXP y_){
>   Rcpp::NumericMatrix X(X_)
>   Rcpp::NumericVector y(y_)
>   return X[y];
> }
>
> R> ss(matrix(rnorm(90),ncol=3),c(1,5,12,22))
>
> It is a bit similar to this question
> http://stackoverflow.com/questions/13038256/subset-of-a-rcpp-matrix-that-matches-a-logical-statement however
> rather than just a single value, the find it for a vector.
>
> also I am not too sure to what extent the Armadillo submat function is
> able to say subset for example rows: 1,5, 12 and 22 and then call the
> resulting matrix something else?
>
> I was hoping that this subsetting procedure was going to be easy...but I
> seem to have got stuck.
>
> thanks
>
> HLM
>
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>



-- 
Yixuan Qiu <yixuan.qiu at cos.name>
Department of Statistics,
Purdue University
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20140303/d9f952a7/attachment.html>


More information about the Rcpp-devel mailing list