第一個函式——再來一次
回想第 1 章的 the_answer() 函式,會固定回傳 42。這次把它改寫成 C++ 檔案。
這個檔案包含以下部分:
- 透過「#include」指令取得
Rcpp的功能。 using namespace宣告,方便輸入程式碼。- 函式定義。
- Rcpp 的 R 註解區塊,用來在 C++ 程式碼編譯後呼叫該函式。
本練習屬於課程
用 Rcpp 最佳化 R 程式碼
練習說明
- 包含
Rcpp.h標頭檔。 - 宣告要使用 Rcpp 命名空間。
- 讓函式回傳
42。 - 在 Rcpp 的 R 註解區塊中呼叫該函式。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
// Include the Rcpp.h header
#include <___>
// Use the Rcpp namespace
using ___ ___;
// [[Rcpp::export]]
int the_answer() {
// Return 42
return ___;
}
/*** R
# Call the_answer() to check you get the right result
___
*/