add-rcpp-integration
정보
이 스킬은 성능 병목 현상을 해결하기 위해 고성능 C++ 코드를 구현할 수 있도록 R 패키지에 Rcpp 또는 RcppArmadillo 통합 기능을 추가합니다. 완전한 설정, 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-integrationClaude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요
문서
Add Rcpp Integration
Integrate C++ code into R package using Rcpp for performance-critical operations.
When Use
- R function too slow and profiling confirms bottleneck
- Need to interface with existing C/C++ libraries
- Implementing algorithms benefit from compiled code (loops, recursion)
- Adding RcppArmadillo for linear algebra operations
Inputs
- Required: Existing R package
- Required: R function to replace or augment with C++
- Optional: External C++ library to interface with
- Optional: Whether to use RcppArmadillo (default: plain Rcpp)
Steps
Step 1: Set Up Rcpp Infrastructure
usethis::use_rcpp()
This:
- Creates
src/directory - Adds
Rcppto LinkingTo and Imports in DESCRIPTION - Creates
R/packagename-package.Rwith@useDynLiband@importFrom Rcpp sourceCpp - Updates
.gitignorefor compiled files
For RcppArmadillo:
usethis::use_rcpp_armadillo()
Got: src/ directory created. DESCRIPTION updated with Rcpp in LinkingTo and Imports. R/packagename-package.R contains @useDynLib directive.
If fail: usethis::use_rcpp() fails? Manually create src/, add LinkingTo: Rcpp and Imports: Rcpp to DESCRIPTION. Add #' @useDynLib packagename, .registration = TRUE and #' @importFrom Rcpp sourceCpp to package-level documentation file.
Step 2: Write C++ Function
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;
}
For 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;
}
Got: C++ source file exists at src/my_function.cpp with valid // [[Rcpp::export]] annotation and roxygen-style //' documentation comments.
If fail: Verify file uses #include <Rcpp.h> (or <RcppArmadillo.h> for Armadillo). Export annotation on its own line directly above function signature. Return types map to valid Rcpp types.
Step 3: Generate RcppExports
Rcpp::compileAttributes()
devtools::document()
Got: R/RcppExports.R and src/RcppExports.cpp generated automatically.
If fail: Check C++ syntax errors. Ensure // [[Rcpp::export]] tag present above each exported function.
Step 4: Verify Compilation
devtools::load_all()
Got: Package compiles and loads without errors.
If fail: Check compiler output for errors. Common issues:
- Missing system headers: Install development libraries
- Syntax errors: C++ compiler messages point to line
- Missing
Rcpp::dependsattribute for RcppArmadillo
Step 5: Write Tests for Compiled Code
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_))
})
Got: Tests pass. Confirm C++ function produces identical results to R equivalent. Handles edge cases (empty vectors, NA values) correctly.
If fail: Tests fail on NA handling? Add explicit NA checks in C++ code using NumericVector::is_na(). Tests fail on empty input? Add guard clause for zero-length vectors at top of function.
Step 6: Add Cleanup Script
Create src/Makevars:
PKG_CXXFLAGS = -O2
Create cleanup in package root (for CRAN):
#!/bin/sh
rm -f src/*.o src/*.so src/*.dll
Make executable: chmod +x cleanup
Got: src/Makevars sets compiler flags. cleanup script removes compiled objects. Both files exist at package root level.
If fail: Verify cleanup has execute permissions (chmod +x cleanup). Makevars uses tabs (not spaces) for indentation if adding Makefile-style rules.
Step 7: Update .Rbuildignore
Ensure compiled artifacts handled:
^src/.*\.o$
^src/.*\.so$
^src/.*\.dll$
Got: .Rbuildignore patterns prevent compiled object files from being included in package tarball. Preserves source files and Makevars.
If fail: Run devtools::check() and look for NOTEs about unexpected files in src/. Adjust .Rbuildignore patterns to exclude only .o, .so, .dll files.
Checks
-
devtools::load_all()compiles without warnings - Compiled function produces correct results
- Tests pass for edge cases (NA, empty, large inputs)
-
R CMD checkpasses with no compilation warnings - RcppExports files generated and committed
- Performance improvement confirmed with benchmarks
Pitfalls
- Forgetting
compileAttributes(): Must regenerate RcppExports after changing C++ files - Integer overflow: Use
doubleinstead ofintfor large numeric values - Memory management: Rcpp handles memory automatically for Rcpp types; don't manually
delete - NA handling: C++ doesn't know about R's NA. Check with
Rcpp::NumericVector::is_na() - Platform portability: Avoid platform-specific C++ features. Test on Windows, macOS, Linux.
- Missing
@useDynLib: Package-level doc must include@useDynLib packagename, .registration = TRUE
See Also
create-r-package- package setup before adding Rcppwrite-testthat-tests- testing compiled functionssetup-github-actions-ci- CI must have C++ toolchainsubmit-to-cran- compiled packages need extra CRAN checks
GitHub 저장소
연관 스킬
content-collections
메타이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.
polymarket
메타이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.
creating-opencode-plugins
메타이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.
sglang
메타SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.
