整数のシーケンス
前の演習で作成した関数は計算を行い、単一の数値を返していました。ベクトルを返す関数を書くこともできます。
ベクトル型を作成する構文は、ベクトルの型、変数名、そしてベクトルの要素数を丸括弧で指定します。たとえば、10 個の要素を含む数値ベクトル numbers を作成するには、次のように書きます。
NumericVector numbers(10);
この演習はコースの一部です
Rcpp で R コードを最適化する
演習の手順
- 2つの整数
loとhiを受け取り、その範囲の数を含むIntegerVectorを返す関数seq_cpp()の定義を完成させてください。- 返り値の型を
IntegerVectorに設定します。 - サイズが
nの整数ベクトルsequenceを作成します。 forループの中で、sequenceの i 番目の要素をloにiを足した値に設定します。sequenceを返します。
- 返り値の型を
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
#include
using namespace Rcpp;
// Set the return type to IntegerVector
// [[Rcpp::export]]
___ seq_cpp(int lo, int hi) {
int n = hi - lo + 1;
// Create a new integer vector, sequence, of size n
___;
for(int i = 0; i < n; i++) {
// Set the ith element of sequence to lo plus i
___;
}
return ___;
}
/*** R
lo <- -2
hi <- 5
seq_cpp(lo, hi)
# Does it give the same answer as R's seq() function?
all.equal(seq_cpp(lo, hi), seq(lo, hi))
*/