MCP HubMCP Hub
SKILL·758B18

add-rcpp-integration

pjt222
업데이트됨 1 month ago
9 조회
26
3
26
GitHub에서 보기
기타general

정보

이 스킬은 R 패키지에 고성능 C++ 코드 구현을 위한 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-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/add-rcpp-integration

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

문서


name: add-rcpp-integration description: > 向 R 包添加 Rcpp 或 RcppArmadillo 集成以实现高性能 C++ 代码。涵盖设置、编写 C++ 函数、RcppExports 生成、编译代码测试和调试。适用于 R 函数过慢且性能分析 确认存在瓶颈时、需要与现有 C/C++ 库交互时,或实现受益于编译代码的算法(循环、 递归、线性代数)时。 license: MIT allowed-tools: Read Write Edit Bash Grep Glob metadata: author: Philipp Thoss version: "1.0" domain: r-packages complexity: advanced language: R tags: r, rcpp, cpp, performance, compiled-code locale: zh-CN source_locale: en source_commit: 6f65f316 translator: claude translation_date: "2026-03-17"

添加 Rcpp 集成

使用 Rcpp 将 C++ 代码集成到 R 包中,用于性能关键操作。

适用场景

  • R 函数过慢且性能分析确认存在瓶颈
  • 需要与现有 C/C++ 库交互
  • 实现受益于编译代码的算法(循环、递归)
  • 添加 RcppArmadillo 用于线性代数操作

输入

  • 必需:现有 R 包
  • 必需:需要用 C++ 替换或增强的 R 函数
  • 可选:要交互的外部 C++ 库
  • 可选:是否使用 RcppArmadillo(默认:纯 Rcpp)

步骤

第 1 步:设置 Rcpp 基础设施

usethis::use_rcpp()

此操作会:

  • 创建 src/ 目录
  • 在 DESCRIPTION 中将 Rcpp 添加到 LinkingTo 和 Imports
  • 创建包含 @useDynLib@importFrom Rcpp sourceCppR/packagename-package.R
  • 更新 .gitignore 以排除编译文件

对于 RcppArmadillo:

usethis::use_rcpp_armadillo()

预期结果: src/ 目录已创建,DESCRIPTION 中 Rcpp 已添加到 LinkingTo 和 Imports,R/packagename-package.R 包含 @useDynLib 指令。

失败处理: 如果 usethis::use_rcpp() 失败,手动创建 src/,在 DESCRIPTION 中添加 LinkingTo: RcppImports: Rcpp,并在包级文档文件中添加 #' @useDynLib packagename, .registration = TRUE#' @importFrom Rcpp sourceCpp

第 2 步:编写 C++ 函数

创建 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/my_function.cpp,具有有效的 // [[Rcpp::export]] 注解和 roxygen 风格的 //' 文档注释。

失败处理: 验证文件使用 #include <Rcpp.h>(或 Armadillo 使用 <RcppArmadillo.h>),导出注解位于函数签名正上方的单独行,且返回类型映射到有效的 Rcpp 类型。

第 3 步:生成 RcppExports

Rcpp::compileAttributes()
devtools::document()

预期结果: R/RcppExports.Rsrc/RcppExports.cpp 自动生成。

失败处理: 检查 C++ 语法错误。确保每个导出函数上方都有 // [[Rcpp::export]] 标签。

第 4 步:验证编译

devtools::load_all()

预期结果: 包编译并加载,无错误。

失败处理: 检查编译器输出中的错误。常见问题:

  • 缺少系统头文件:安装开发库
  • 语法错误:C++ 编译器消息指向具体行
  • RcppArmadillo 缺少 Rcpp::depends 属性

第 5 步:编写编译代码的测试

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_))
})

预期结果: 测试通过,确认 C++ 函数产生与 R 等价物相同的结果,并正确处理边界情况(空向量、NA 值)。

失败处理: 如果 NA 处理测试失败,在 C++ 代码中使用 NumericVector::is_na() 添加显式 NA 检查。如果空输入测试失败,在函数顶部添加零长度向量的保护子句。

第 6 步:添加清理脚本

创建 src/Makevars

PKG_CXXFLAGS = -O2

在包根目录创建 cleanup(用于 CRAN):

#!/bin/sh
rm -f src/*.o src/*.so src/*.dll

设为可执行:chmod +x cleanup

预期结果: src/Makevars 设置编译器标志,cleanup 脚本删除编译对象。两个文件都存在于包根目录级别。

失败处理: 验证 cleanup 具有执行权限(chmod +x cleanup),且如果添加 Makefile 风格的规则,Makevars 使用制表符(而非空格)缩进。

第 7 步:更新 .Rbuildignore

确保编译产物被正确处理:

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

预期结果: .Rbuildignore 模式阻止编译对象文件被包含在包 tarball 中,同时保留源文件和 Makevars。

失败处理: 运行 devtools::check() 并查找关于 src/ 中意外文件的 NOTE。调整 .Rbuildignore 模式以仅排除 .o.so.dll 文件。

验证清单

  • devtools::load_all() 编译无警告
  • 编译函数产生正确结果
  • 边界情况测试通过(NA、空、大输入)
  • R CMD check 通过,无编译警告
  • RcppExports 文件已生成并提交
  • 基准测试确认性能改进

常见问题

  • 忘记 compileAttributes():更改 C++ 文件后必须重新生成 RcppExports
  • 整数溢出:对于大数值使用 double 而不是 int
  • 内存管理:Rcpp 自动处理 Rcpp 类型的内存;不要手动 delete
  • NA 处理:C++ 不了解 R 的 NA。使用 Rcpp::NumericVector::is_na() 检查
  • 平台可移植性:避免平台特定的 C++ 特性。在 Windows、macOS 和 Linux 上测试
  • 缺少 @useDynLib:包级文档必须包含 @useDynLib packagename, .registration = TRUE

相关技能

  • create-r-package — 添加 Rcpp 之前的包设置
  • write-testthat-tests — 测试编译函数
  • setup-github-actions-ci — CI 必须有 C++ 工具链
  • submit-to-cran — 编译包需要额外的 CRAN 检查

GitHub 저장소

pjt222/agent-almanac
경로: i18n/zh-CN/skills/add-rcpp-integration
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams
FAQ

Frequently asked questions

What is the add-rcpp-integration skill?

add-rcpp-integration is a Claude Skill by pjt222. Skills package instructions and resources that Claude loads on demand, so Claude can perform add-rcpp-integration-related tasks without extra prompting.

How do I install add-rcpp-integration?

Use the install commands on this page: add add-rcpp-integration to Claude Code as a plugin, or clone its repository into your skills directory, then restart Claude so it picks up the skill.

What category does add-rcpp-integration belong to?

add-rcpp-integration is in the Other category, tagged general.

Is add-rcpp-integration free to use?

Yes. add-rcpp-integration is listed on AIMCP and free to install. It runs inside Claude, so no separate service account is required to use the skill itself.

연관 스킬

llamaguard
기타

LlamaGuard는 폭력 및 혐오 발언 등 6가지 안전 범주에서 LLM 입력과 출력을 조정하기 위한 Meta의 70-80억 파라미터 모델입니다. 94-95% 정확도를 제공하며 vLLM, Hugging Face 또는 Amazon SageMaker를 사용해 배포할 수 있습니다. 이 기술을 사용하여 AI 애플리케이션에 콘텐츠 필터링 및 안전 가드레일을 손쉽게 통합하세요.

스킬 보기
cost-optimization
기타

이 Claude Skill은 리소스 적정화, 태깅 전략, 지출 분석을 통해 개발자들이 클라우드 비용을 최적화할 수 있도록 지원합니다. AWS, Azure, GCP에서 클라우드 비용을 절감하고 비용 거버넌스를 구현하기 위한 프레임워크를 제공합니다. 인프라 비용을 분석하거나, 리소스를 적정화하거나, 예산 제약을 충족해야 할 때 사용하세요.

스킬 보기
sports-betting-analyzer
기타

이 Claude Skill은 스프레드, 오버/언더, 프로프 베트를 포함한 스포츠 베팅 시장을 분석합니다. 역사적 추이와 상황별 통계를 검토하여 가치 베트를 발견하고, 교육적 목적으로 실행 가능한 권장 사항이 담긴 구조화된 마크다운 결과를 제공합니다. 개발자는 이 기능을 스포츠 베팅 분석 도구에 활용할 수 있으며, 단순히 엔터테인먼트/교육 목적으로만 설계되었음을 유의해야 합니다.

스킬 보기
quantizing-models-bitsandbytes
기타

이 스킬은 bitsandbytes를 사용하여 LLM을 8비트 또는 4비트 정밀도로 양자화하며, 최소한의 정확도 손실로 50-75%의 메모리 감소를 달성합니다. 제한된 GPU 메모리에서 더 큰 모델을 실행하거나 추론을 가속화하는 데 이상적이며, INT8, NF4, FP4와 같은 형식을 지원합니다. 이 스킬은 HuggingFace Transformers와 통합되어 QLoRA 학습 및 8비트 옵티마이저를 가능하게 합니다.

스킬 보기