MCP HubMCP Hub
스킬 목록으로 돌아가기

add-rcpp-integration

pjt222
업데이트됨 2 days ago
1 조회
17
2
17
GitHub에서 보기
메타testing

정보

이 스킬은 R 패키지에 Rcpp 또는 RcppArmadillo 통합을 추가하여 병목 현상, 라이브러리 인터페이싱 또는 복잡한 알고리즘을 위한 고성능 C++ 코드를 가능하게 합니다. 개발자에게 설정, C++ 함수 작성, RcppExports 생성 및 컴파일된 코드 테스트 과정을 안내합니다. 프로파일링 결과 R 함수가 너무 느리다고 확인되거나 루프, 재귀, 선형 대수 연산을 위해 컴파일된 코드를 활용해야 할 때 사용하세요.

빠른 설치

Claude Code

추천
기본
npx skills add pjt222/agent-almanac -a claude-code
플러그인 명령대체
/plugin add https://github.com/pjt222/agent-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/add-rcpp-integration

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Add Rcpp Integration

Integrate C++ code into an R package using Rcpp for performance-critical operations.

When to Use

  • R function is too slow and profiling confirms a bottleneck
  • Need to interface with existing C/C++ libraries
  • Implementing algorithms that 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)

Procedure

Step 1: Set Up Rcpp Infrastructure

usethis::use_rcpp()

This:

  • Creates src/ directory
  • Adds Rcpp to LinkingTo and Imports in DESCRIPTION
  • Creates R/packagename-package.R with @useDynLib and @importFrom Rcpp sourceCpp
  • Updates .gitignore for compiled files

For RcppArmadillo:

usethis::use_rcpp_armadillo()

Got: src/ directory created, DESCRIPTION updated with Rcpp in LinkingTo and Imports, and R/packagename-package.R contains @useDynLib directive.

If fail: If usethis::use_rcpp() fails, manually create src/, add LinkingTo: Rcpp and Imports: Rcpp to DESCRIPTION, and add #' @useDynLib packagename, .registration = TRUE and #' @importFrom Rcpp sourceCpp to the 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 the file uses #include <Rcpp.h> (or <RcppArmadillo.h> for Armadillo), that the export annotation is on its own line directly above the function signature, and that 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 is 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 the line
  • Missing Rcpp::depends attribute 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, confirming the C++ function produces identical results to the R equivalent and handles edge cases (empty vectors, NA values) correctly.

If fail: If tests fail on NA handling, add explicit NA checks in the C++ code using NumericVector::is_na(). If tests fail on empty input, add a guard clause for zero-length vectors at the top of the 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 and cleanup script removes compiled objects. Both files exist at the package root level.

If fail: Verify cleanup has execute permissions (chmod +x cleanup) and that Makevars uses tabs (not spaces) for indentation if adding Makefile-style rules.

Step 7: Update .Rbuildignore

Ensure compiled artifacts are handled:

^src/.*\.o$
^src/.*\.so$
^src/.*\.dll$

Got: .Rbuildignore patterns prevent compiled object files from being included in the package tarball, while preserving 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, and .dll files.

Validation

  • devtools::load_all() compiles without warnings
  • Compiled function produces correct results
  • Tests pass for edge cases (NA, empty, large inputs)
  • R CMD check passes with no compilation warnings
  • RcppExports files are generated and committed
  • Performance improvement confirmed with benchmarks

Pitfalls

  • Forgetting compileAttributes(): Must regenerate RcppExports after changing C++ files
  • Integer overflow: Use double instead of int for 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, and Linux.
  • Missing @useDynLib: The package-level doc must include @useDynLib packagename, .registration = TRUE

Related Skills

  • create-r-package - package setup before adding Rcpp
  • write-testthat-tests - testing compiled functions
  • setup-github-actions-ci - CI must have C++ toolchain
  • submit-to-cran - compiled packages need extra CRAN checks

GitHub 저장소

pjt222/agent-almanac
경로: i18n/caveman-lite/skills/add-rcpp-integration
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

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을 선택하십시오.

스킬 보기