Rcpp 中的整数序列
Sequence of Integers in Rcpp
我想创建一个整数序列用于矩阵内的索引。 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(first, last)
调用的 R 的 seq
函数。
已提供有关 C++11 函数 std::iota
的文档 here。
seq_along
接受一个向量,你要使用的是seq
结合min
和max
,两者都接受向量。 seq
returns 一个 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
我想创建一个整数序列用于矩阵内的索引。 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(first, last)
调用的 R 的 seq
函数。
已提供有关 C++11 函数 std::iota
的文档 here。
seq_along
接受一个向量,你要使用的是seq
结合min
和max
,两者都接受向量。 seq
returns 一个 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