loki - 3 months ago 37
R Question

Sequence of Integers in Rcpp

I want to create a sequence of integer numbers for indexing within a matrix. The

`R`
pendant would be:

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

This is what i have tried in
`Rcpp`
to create the sequence of integers:

``````#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));
}
``````

however I get the Error message:

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

how can I create a sequence of integers in Rcpp?

Quite clearly, R and C++ are different programming languages. The R function `seq_along` is not valid C++ code. It therefore cannot be used within an Rcpp code.

Here is a possible Rcpp implementation :

``````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
``````

This code generates a function `myseq` which takes two arguments: The first and the last number in an integer series. It corresponds to R's `seq` function called with two arguments `seq(first, last)`.

A documentation on the C++11 function `std::iota` is given here.

Source (Stackoverflow)