问题
I'm coding with RcppArmadillo
and got stuck with a very basic question. Suppose I have a vector "v", and I want to take its first 10 elements, like in R: v[1:10]
. Since 1:10
doesn't work in RcppArmadillo
, I tried v.elem(seq_len(10))
, but it didn't work. Any hint?
回答1:
Assuming you're taking about an arma::vec
, this should work:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::vec f(const arma::vec & v, int first, int last) {
arma::vec out = v.subvec(first, last);
return out;
}
/*** R
f(11:20, 3, 6)
*/
Note that this uses zero-based indexing (11
is the 0th element of the vector). Coerce to NumericVector
as desired.
When source'ed into R, the code is compiled, linked, loaded and the embedded example is executed:
R> sourceCpp("/tmp/armaEx.cpp")
R> f(11:20, 3, 6)
[,1]
[1,] 14
[2,] 15
[3,] 16
[4,] 17
R>
So it all really is _just one call to subvec()
. See the Armadillo documentation for more.
来源:https://stackoverflow.com/questions/29640048/a-simple-rcpparmadillo-index-issue