Rcpp中的整数序列

问题描述 投票:3回答:2

我想创建一个整数序列,用于在矩阵中进行索引。 R吊坠将是:

indexRow <- max(0,1):min(2,12)
matrix1[indexRow, ]

这是我在Rcpp中尝试创建整数序列的原因:

#include <Rcpp.h>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace Rcpp;
using namespace std;


// [[Rcpp::export]]
NumericVector test(NumericVector x) {
  IntegerVector indexRow = Rcpp::seq_along(max(0, 1), min(1, 12));
}

但是我收到错误消息:

no matching function for call to 'seq_along(const int&, const int&)'

如何在Rcpp中创建一个整数序列?

r sequence rcpp
2个回答
5
投票

这是一个可能的Rcpp实现:

library(Rcpp)
cppFunction(plugins='cpp11','NumericVector myseq(int &first, int &last) {
NumericVector y(abs(last - first) + 1);
if (first < last) 
   std::iota(y.begin(), y.end(), first);
else {
   std::iota(y.begin(), y.end(), last);
   std::reverse(y.begin(), y.end());
 }
return y;
}')
#> myseq(max(0,1), min(13,17))
#[1]  1  2  3  4  5  6  7  8  9 10 11 12 13

此代码生成一个函数myseq,它接受两个参数:整数系列中的第一个和最后一个数字。它类似于用两个整数参数seq调用的R的seq(first, last)函数。

有关C ++ 11函数std::iota的文档给出了here


4
投票

seq_along接受一个向量,你想要使用的是seq结合minmax,两者都采取向量。 seq返回IntegerVector。这是一个例子。

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerVector test(IntegerVector a, IntegerVector b) {
  IntegerVector vec =  seq(max(a), min(b));
 return vec;
}

R你用

> test(c(0,1), c(2,12))
[1] 1 2
© www.soinside.com 2019 - 2024. All rights reserved.