我想创建一个整数序列,用于在矩阵中进行索引。 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中创建一个整数序列?
这是一个可能的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。
seq_along
接受一个向量,你想要使用的是seq
结合min
和max
,两者都采取向量。 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