整数序列
您在之前练习中编写的函数会先计算,然后返回一个单一的数字。您也可以编写返回向量的函数。
创建向量类型的语法是:先写向量的类型,其次是变量名,随后在括号中写入向量的元素个数。例如,若要创建一个名为 numbers、包含 10 个元素的数值向量,代码如下所示。
NumericVector numbers(10);
本练习是课程的一部分
用 Rcpp 优化 R 代码
练习说明
- 完成函数
seq_cpp()的定义。它接收两个整数lo和hi,并返回它们之间数字构成的IntegerVector。- 将返回类型设为
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))
*/