開始使用免費開始

整數序列

你在前面幾個練習中所寫的函式,會先進行計算,然後回傳單一數值。你也可以撰寫會回傳向量的函式。

建立向量型別的語法是:指定向量的型別,加上變數名稱,然後在括號中填入向量的元素個數。例如,若要建立一個名為 numbers、包含 10 個元素的數值向量,程式碼如下:

NumericVector numbers(10);

本練習屬於課程

用 Rcpp 最佳化 R 程式碼

檢視課程

練習說明

  • 完成函式 seq_cpp() 的定義。它接收兩個整數 lohi,並回傳介於兩者之間的 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))
*/
編輯並執行程式碼