[Rcpp-devel] Indexing a vector by a vector of indices
Søren Højsgaard
sorenh at math.aau.dk
Fri May 31 14:00:59 CEST 2013
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)?
Cheers
Søren
More information about the Rcpp-devel
mailing list