add-rcpp-integration
について
このスキルは、RcppまたはRcppArmadilloをRパッケージに統合し、パフォーマンスが重要なR関数を高性能なC++コードに置き換える手法を扱います。セットアップからC++関数の記述、RcppExportsの生成、テスト、デバッグに至る完全なワークフローを網羅しています。プロファイリングによってRのボトルネックが確認された場合、既存のC/C++ライブラリとの連携が必要な場合、あるいはループや線形代数のようなコンパイルによる恩恵を受けるアルゴリズムを実装する際に活用してください。
クイックインストール
Claude Code
推奨npx skills add pjt222/agent-almanac -a claude-code/plugin add https://github.com/pjt222/agent-almanacgit clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/add-rcpp-integrationこのコマンドをClaude Codeにコピー&ペーストしてスキルをインストールします
ドキュメント
Add Rcpp Integration
Integrate C++ into R pkg via Rcpp → perf-critical ops.
Use When
- R fn too slow, profile confirms bottleneck
- Interface existing C/C++ libs
- Algos benefit compiled (loops, recursion)
- RcppArmadillo → linear algebra
In
- Required: Existing R pkg
- Required: R fn to replace/augment w/ C++
- Optional: External C++ lib
- Optional: RcppArmadillo? (default: plain Rcpp)
Do
Step 1: Rcpp Infra Setup
usethis::use_rcpp()
Does:
- Creates
src/dir - Adds
Rcpp→ LinkingTo + Imports in DESCRIPTION - Creates
R/packagename-package.Rw/@useDynLib+@importFrom Rcpp sourceCpp - Updates
.gitignorefor compiled
RcppArmadillo:
usethis::use_rcpp_armadillo()
→ src/ created, DESCRIPTION updated Rcpp LinkingTo + Imports, R/packagename-package.R has @useDynLib.
If err: usethis::use_rcpp() fails → manually create src/, add LinkingTo: Rcpp + Imports: Rcpp, add #' @useDynLib packagename, .registration = TRUE + #' @importFrom Rcpp sourceCpp to pkg doc file.
Step 2: Write C++ Fn
Create src/my_function.cpp:
#include <Rcpp.h>
using namespace Rcpp;
//' Compute cumulative sum efficiently
//'
//' @param x A numeric vector
//' @return A numeric vector of cumulative sums
//' @export
// [[Rcpp::export]]
NumericVector cumsum_cpp(NumericVector x) {
int n = x.size();
NumericVector out(n);
out[0] = x[0];
for (int i = 1; i < n; i++) {
out[i] = out[i - 1] + x[i];
}
return out;
}
RcppArmadillo:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
//' Matrix multiplication using Armadillo
//'
//' @param A A numeric matrix
//' @param B A numeric matrix
//' @return The matrix product A * B
//' @export
// [[Rcpp::export]]
arma::mat mat_mult(const arma::mat& A, const arma::mat& B) {
return A * B;
}
→ C++ src at src/my_function.cpp w/ valid // [[Rcpp::export]] + roxygen //' docs.
If err: Verify #include <Rcpp.h> (or <RcppArmadillo.h>), export annotation own line directly above signature, return types map valid Rcpp.
Step 3: Generate RcppExports
Rcpp::compileAttributes()
devtools::document()
→ R/RcppExports.R + src/RcppExports.cpp auto-generated.
If err: Check C++ syntax. Ensure // [[Rcpp::export]] above each exported fn.
Step 4: Verify Compilation
devtools::load_all()
→ Pkg compiles + loads no err.
If err: Check compiler out. Common:
- Missing system headers → install dev libs
- Syntax err → compiler msgs point to line
- Missing
Rcpp::dependsfor RcppArmadillo
Step 5: Tests for Compiled
test_that("cumsum_cpp matches base R", {
x <- c(1, 2, 3, 4, 5)
expect_equal(cumsum_cpp(x), cumsum(x))
})
test_that("cumsum_cpp handles edge cases", {
expect_equal(cumsum_cpp(numeric(0)), numeric(0))
expect_equal(cumsum_cpp(c(NA_real_, 1)), c(NA_real_, NA_real_))
})
→ Tests pass → C++ identical to R + edge cases (empty, NA) correct.
If err: NA fail → add explicit NA checks via NumericVector::is_na(). Empty fail → guard clause zero-length at top.
Step 6: Cleanup Script
Create src/Makevars:
PKG_CXXFLAGS = -O2
Create cleanup in pkg root (CRAN):
#!/bin/sh
rm -f src/*.o src/*.so src/*.dll
Make executable: chmod +x cleanup
→ src/Makevars sets compiler flags, cleanup removes objects. Both at pkg root.
If err: Verify cleanup has exec perms (chmod +x cleanup), Makevars tabs (not spaces) for Makefile rules.
Step 7: Update .Rbuildignore
Handle compiled artifacts:
^src/.*\.o$
^src/.*\.so$
^src/.*\.dll$
→ .Rbuildignore patterns prevent compiled objects in tarball, preserve src + Makevars.
If err: devtools::check() → NOTEs about unexpected files in src/. Adjust patterns → exclude only .o, .so, .dll.
Check
-
devtools::load_all()compiles no warn - Compiled fn produces correct results
- Tests pass edge cases (NA, empty, large)
-
R CMD checkpasses no compile warn - RcppExports generated + committed
- Perf improvement via benchmarks
Traps
- Forget
compileAttributes(): Must regen RcppExports after C++ changes - Int overflow:
doublenotintfor large numerics - Memory mgmt: Rcpp auto-handles for Rcpp types; no manual
delete - NA handling: C++ doesn't know R's NA. Check
Rcpp::NumericVector::is_na() - Platform portability: Avoid platform-specific C++. Test Win, macOS, Linux.
- Missing
@useDynLib: Pkg doc must@useDynLib packagename, .registration = TRUE
→
create-r-package— pkg setup before Rcppwrite-testthat-tests— testing compiled fnssetup-github-actions-ci— CI needs C++ toolchainsubmit-to-cran— compiled pkgs need extra CRAN checks
GitHub リポジトリ
関連スキル
content-collections
メタこのスキルは、Content Collections(Markdown/MDXファイルを型安全なデータコレクションに変換するTypeScriptファーストのツール)の本番環境でテストされた設定を提供します。Zodバリデーションによる型安全性を実現し、ブログ、ドキュメントサイト、コンテンツ重視のVite + Reactアプリケーション構築時にご利用ください。Viteプラグインの設定、MDXコンパイルから、デプロイ最適化、スキーマバリデーションまで、すべてを網羅しています。
polymarket
メタこのスキルは、開発者がPolymarket予測市場プラットフォームを活用したアプリケーション構築を可能にします。API統合による取引や市場データの取得に加え、WebSocketを介したリアルタイムデータストリーミングにより、ライブ取引や市場活動を監視できます。取引戦略の実装や、ライブ市場更新を処理するツールの作成にご利用ください。
creating-opencode-plugins
メタこのスキルは、開発者がコマンド、ファイル、LSP操作など25種類以上のイベントタイプにフックするOpenCodeプラグインを作成することを支援します。JavaScript/TypeScriptモジュール向けに、プラグイン構造、イベントAPI仕様、および実装パターンを提供します。カスタムイベント駆動ロジックでOpenCode AIアシスタントのライフサイクルをインターセプト、監視、または拡張する必要がある場合にご利用ください。
sglang
メタSGLangは、高性能なLLMサービングフレームワークであり、RadixAttentionプレフィックスキャッシュを活用したJSON、正規表現、エージェントワークフロー向けの高速で構造化された生成を特長とします。特にプレフィックスが繰り返されるタスクにおいて、大幅に高速な推論を実現し、複雑な構造化出力やマルチターン対話に最適です。制約付きデコードが必要な場合や、広範なプレフィックス共有を伴うアプリケーションを構築する場合は、vLLMなどの代替案ではなくSGLangを選択してください。
