A simple RcppArmadillo index issue

岁酱吖の 提交于 2021-01-29 16:56:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!