[Rcpp-devel] Indexing a vector by a vector of indices
Dirk Eddelbuettel
edd at debian.org
Fri May 31 19:33:31 CEST 2013
On 31 May 2013 at 12:00, Søren Højsgaard wrote:
| Dear all;
|
| In c++ I want to do:
| x<-c(2,4,6,8,10)
| i<- c(2,3,5)
| x[i]
|
| I do:
|
| cat("
| #include <RcppArmadillo.h>
|
| using namespace Rcpp;
| using namespace arma;
|
| // [[Rcpp::export]]
| NumericVector select(NumericVector vec_, NumericVector idx_){
| arma::vec vv = Rcpp::as<arma::vec>(vec_);
| arma::uvec ii = Rcpp::as<arma::uvec>(idx_);
| arma::vec aa = vv.elem(ii-1);
| Rcpp::NumericVector bb(as<Rcpp::NumericMatrix>(wrap(aa)));
| return Rcpp::wrap( bb );
| }
| ", file="select.cpp")
|
| Rcpp::sourceCpp('./select.cpp')
| select(x, i)
|
| [,1]
| [1,] 4
| [2,] 6
| [3,] 10
|
| Two things: 1) there must be easier ways and 2) why is the result a matrix and not a vector (i.e. why does the result have a dim attribute)?
1) Yes, see the Rcpp Gallery, there are two pieces you want to read,
particularly
http://gallery.rcpp.org/articles/armadillo-subsetting/
which uses Armadillo, and maybe also
http://gallery.rcpp.org/articles/stl-transform-for-subsetting/
which uses an STL trick I realized.
2) Methinks that is an error on your part where you use
Rcpp::NumericVector bb(as<Rcpp::NumericMatrix>(wrap(aa)));
you probably meant
Rcpp::NumericVector bb(as<Rcpp::NumericVector>(wrap(aa)));
Best, Dirk
--
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
More information about the Rcpp-devel
mailing list