如何为元素 2 到 101 切片 Rcpp NumericVector? [英] How to slice Rcpp NumericVector for elements 2 to 101?

查看:34
本文介绍了如何为元素 2 到 101 切片 Rcpp NumericVector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为元素 2 到 101 切片 Rcpp 的 NumericVector

Hi I'm trying to slice Rcpp's NumericVector for elements 2 to 101

在 R 中,我会这样做:

in R, I would do this:

array[2:101]

我如何在 RCpp 中做同样的事情?

How do I do the same in RCpp?

我试着看这里:http://gallery.rcpp.org/articles/subsetting/但是该资源有一个示例,该示例使用 IntegerVector::create() 列出了所有元素.但是,::create() 受元素数量的限制.(除了乏味之外).有没有办法在给定 2 个索引的情况下对向量进行切片?

I tried looking here: http://gallery.rcpp.org/articles/subsetting/ But the resource has an example that lists all the elements using IntegerVector::create(). However, ::create() is limited by the number of elements. (in addition to being tedious). Any way to slice a vector given 2 indices?

推荐答案

这可以通过 RcppRange 函数实现.这会生成等效的 C++ 位置索引序列.例如

This is possible with Rcpp's Range function. This generates the equivalent C++ positional index sequence. e.g.

Rcpp::Range(0, 3)

会给:

0 1 2 3

注意:C++ 索引从 0 开始,而不是 1!

Note: C++ indices begin at 0 not 1!

示例:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector subset_range(Rcpp::NumericVector x,
                                 int start = 1, int end = 100) {

  // Use the Range function to create a positional index sequence
  return x[Rcpp::Range(start, end)];
}

/***R
x = rnorm(101)

# Note: C++ indices start at 0 not 1!
all.equal(x[2:101], subset_range(x, 1, 100))
*/

这篇关于如何为元素 2 到 101 切片 Rcpp NumericVector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆