一个简单的RcppArmadillo索引问题 [英] A simple RcppArmadillo index issue
问题描述
我正在使用 RcppArmadillo
进行编码,并且陷入了一个非常基本的问题.假设我有一个向量"v",并且我想采用它的前10个元素,例如R: v [1:10]
.由于 1:10
在 RcppArmadillo
中不起作用,因此我尝试了 v.elem(seq_len(10))
,但它没有起作用.有提示吗?
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?
推荐答案
假设您要使用 arma :: vec
,这应该可行:
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)
*/
请注意,这使用了从零开始的索引( 11
是向量的第0个元素).根据需要强制使用 NumericVector
.
Note that this uses zero-based indexing (11
is the 0th element of the vector). Coerce to NumericVector
as desired.
将源代码放入R中时,将对代码进行编译,链接,加载并执行嵌入式示例:
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>
所以这实际上只是_一次调用 subvec()
.有关更多信息,请参见Armadillo文档.
So it all really is _just one call to subvec()
. See the Armadillo documentation for more.
这篇关于一个简单的RcppArmadillo索引问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!