r-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

R Package Development

R包开发

Use this skill when working with R packages to ensure proper development workflows, testing patterns, and documentation standards.
当你进行R包开发时使用本技能,以确保遵循规范的开发工作流、测试模式和文档标准。

Development Workflow

开发工作流

R Environment

R环境

  • Use radian with R as an alias so call R scripts using Rscript
  • Do not run devtools::test with grep; read the whole output
  • 将radian设为R的别名,以便通过Rscript调用R脚本
  • 不要用grep来运行devtools::test;请查看完整输出

Package Building and Management

包构建与管理

r
undefined
r
undefined

Load package for interactive development

Load package for interactive development

devtools::load_all()
devtools::load_all()

Update documentation (REQUIRED before committing R changes)

Update documentation (REQUIRED before committing R changes)

devtools::document()
devtools::document()

Run all tests

Run all tests

devtools::test()
devtools::test()

Run specific test file

Run specific test file

testthat::test_file("tests/testthat/test-filename.R")
testthat::test_file("tests/testthat/test-filename.R")

Run tests matching a pattern

Run tests matching a pattern

devtools::test(filter = "pattern") testthat::test_local(filter = "pattern")
devtools::test(filter = "pattern") testthat::test_local(filter = "pattern")

Check package (R CMD check)

Check package (R CMD check)

devtools::check()
devtools::check()

Build package

Build package

devtools::build()
devtools::build()

Install package locally

Install package locally

devtools::install()
devtools::install()

Check with vignettes built

Check with vignettes built

devtools::check(build_args = c("--compact-vignettes=both"))
undefined
devtools::check(build_args = c("--compact-vignettes=both"))
undefined

Code Quality and Style

代码质量与风格

r
undefined
r
undefined

Lint package (configuration in .lintr)

Lint package (configuration in .lintr)

lintr::lint_package()
lintr::lint_package()

Lint specific file

Lint specific file

lintr::lint("R/filename.R")
lintr::lint("R/filename.R")

Style code (pre-commit hook typically uses tidyverse style)

Style code (pre-commit hook typically uses tidyverse style)

styler::style_pkg()
styler::style_pkg()

Check test coverage

Check test coverage

covr::package_coverage()
undefined
covr::package_coverage()
undefined

Documentation Building

文档构建

r
undefined
r
undefined

Build vignettes

Build vignettes

devtools::build_vignettes()
devtools::build_vignettes()

Build specific vignette

Build specific vignette

rmarkdown::render("vignettes/name.Rmd")
rmarkdown::render("vignettes/name.Rmd")

Build pkgdown site locally

Build pkgdown site locally

pkgdown::build_site()
undefined
pkgdown::build_site()
undefined

Testing Best Practices

测试最佳实践

testthat Patterns

testthat 模式

Preferred expectations:
  • expect_identical()
    >
    expect_equal()
    (when exact match expected)
  • Multiple
    expect_true()
    calls > stacking conditions with
    &&
  • expect_s3_class()
    >
    expect_true(inherits(...))
  • Use specific
    expect_*
    functions:
    • expect_lt()
      ,
      expect_gt()
      ,
      expect_lte()
      ,
      expect_gte()
    • expect_length()
    • expect_named()
    • expect_type()
Examples:
r
undefined
推荐的断言方式:
  • expect_identical()
    >
    expect_equal()
    (当需要完全匹配时)
  • 多次调用
    expect_true()
    优于用
    &&
    堆叠条件
  • expect_s3_class()
    >
    expect_true(inherits(...))
  • 使用特定的
    expect_*
    函数:
    • expect_lt()
      ,
      expect_gt()
      ,
      expect_lte()
      ,
      expect_gte()
    • expect_length()
    • expect_named()
    • expect_type()
示例:
r
undefined

Good

Good

expect_identical(result, expected) expect_s3_class(obj, "data.frame") expect_lt(value, 10) expect_true(condition1) expect_true(condition2)
expect_identical(result, expected) expect_s3_class(obj, "data.frame") expect_lt(value, 10) expect_true(condition1) expect_true(condition2)

Avoid

Avoid

expect_equal(result, expected) # when identical match is needed expect_true(inherits(obj, "data.frame")) expect_true(value < 10) expect_true(condition1 && condition2)
undefined
expect_equal(result, expected) # when identical match is needed expect_true(inherits(obj, "data.frame")) expect_true(value < 10) expect_true(condition1 && condition2)
undefined

Test Organisation

测试组织

  • Use testthat edition 3
  • Test files named
    test-{component}.R
  • Helper files in
    tests/testthat/helper-{name}.R
  • Setup files in
    tests/testthat/setup.R
    for shared fixtures
  • Custom expectations in
    tests/testthat/helper-expectations.R
  • 使用testthat第3版
  • 测试文件命名为
    test-{组件名}.R
  • 辅助文件放在
    tests/testthat/helper-{名称}.R
  • 共享测试环境的设置文件放在
    tests/testthat/setup.R
  • 自定义断言放在
    tests/testthat/helper-expectations.R

Conditional Testing

条件测试

r
undefined
r
undefined

Skip tests on CRAN

Skip tests on CRAN

testthat::skip_on_cran()
testthat::skip_on_cran()

Skip if not on CI

Skip if not on CI

testthat::skip_if_not(on_ci())
testthat::skip_if_not(on_ci())

Skip if package not available

Skip if package not available

testthat::skip_if_not_installed("package")
undefined
testthat::skip_if_not_installed("package")
undefined

Documentation Standards

文档标准

roxygen2 Best Practices

roxygen2 最佳实践

Avoid duplication with
@inheritParams
:
r
#' @param x Input data
#' @param ... Additional arguments
my_function <- function(x, ...) {}

#' @inheritParams my_function
#' @param y Another parameter
wrapper_function <- function(x, y, ...) {}
Documentation structure:
  • One sentence per line in descriptions
  • Max 80 characters per line
  • Use
    @family
    tags for related functions
  • Use
    @examples
    or
    @examplesIf
    for examples
  • UK English spelling
Example documentation:
r
#' Process input data
#'
#' This function processes the input data according to specified parameters.
#' It returns a processed data frame with additional columns.
#'
#' @param data A data.frame containing the input data
#' @param method Character string specifying the processing method
#'
#' @return A data.frame with processed results
#'
#' @family preprocessing
#'
#' @examples
#' \dontrun{
#' result <- process_data(my_data, method = "standard")
#' }
#'
#' @export
process_data <- function(data, method = "standard") {
  # implementation
}
使用
@inheritParams
避免重复:
r
#' @param x Input data
#' @param ... Additional arguments
my_function <- function(x, ...) {}

#' @inheritParams my_function
#' @param y Another parameter
wrapper_function <- function(x, y, ...) {}
文档结构:
  • 描述部分每行一句话
  • 每行最多80个字符
  • 为相关函数使用
    @family
    标签
  • 使用
    @examples
    @examplesIf
    添加示例
  • 使用英式英语拼写
文档示例:
r
#' Process input data
#'
#' This function processes the input data according to specified parameters.
#' It returns a processed data frame with additional columns.
#'
#' @param data A data.frame containing the input data
#' @param method Character string specifying the processing method
#'
#' @return A data.frame with processed results
#'
#' @family preprocessing
#'
#' @examples
#' \dontrun{
#' result <- process_data(my_data, method = "standard")
#' }
#'
#' @export
process_data <- function(data, method = "standard") {
  # implementation
}

Code Style Guidelines

代码风格指南

Naming Conventions

命名规范

  • Internal functions: Prefix with
    .
    r
    .internal_helper <- function() {}
  • Exported functions: Use snake_case
    r
    public_function <- function() {}
  • 内部函数:以
    .
    作为前缀
    r
    .internal_helper <- function() {}
  • 导出函数:使用蛇形命名法(snake_case)
    r
    public_function <- function() {}

Formatting

格式规范

  • Max 80 characters per line
  • No trailing whitespace
  • No spurious blank lines
  • Use tidyverse style guide
  • Set up pre-commit hooks for automatic formatting
  • 每行最多80个字符
  • 无尾随空格
  • 无多余空行
  • 遵循tidyverse风格指南
  • 设置pre-commit钩子以自动格式化代码

Pre-commit Hooks

Pre-commit 钩子

Typical
.pre-commit-config.yaml
includes:
  • style-files
    : Auto-format R code
  • lintr
    : Lint R code
  • readme-rmd-rendered
    : Ensure README.md is up-to-date
  • parsable-R
    : Check R syntax
  • deps-in-desc
    : Check dependencies are in DESCRIPTION
bash
undefined
典型的
.pre-commit-config.yaml
包含:
  • style-files
    :自动格式化R代码
  • lintr
    :检查R代码规范
  • readme-rmd-rendered
    :确保README.md是最新版本
  • parsable-R
    :检查R语法
  • deps-in-desc
    :检查依赖是否已添加到DESCRIPTION文件中
bash
undefined

Install pre-commit

Install pre-commit

pip install pre-commit
pip install pre-commit

Install hooks

Install hooks

pre-commit install
pre-commit install

Run manually

Run manually

pre-commit run --all-files
undefined
pre-commit run --all-files
undefined

Common Data Structures

常用数据结构

data.table Usage

data.table 使用规范

Many R packages use
data.table
for performance:
  • Functions often expect/return
    data.table
    objects
  • Use
    data.table::setDT()
    or custom
    coerce_dt()
    to ensure input is data.table
  • Set keys for efficient joins:
    data.table::setkey(dt, col)
  • Use
    :=
    for in-place modification
许多R包为了提升性能会使用
data.table
  • 函数通常期望输入/返回
    data.table
    对象
  • 使用
    data.table::setDT()
    或自定义的
    coerce_dt()
    确保输入为data.table类型
  • 为高效连接设置键:
    data.table::setkey(dt, col)
  • 使用
    :=
    进行原地修改

S3 Classes

S3类

  • Check class with
    inherits()
    or
    expect_s3_class()
  • Document S3 methods properly
  • Export constructors, not internal class definitions
  • 使用
    inherits()
    expect_s3_class()
    检查类
  • 正确记录S3方法
  • 导出构造函数,而非内部类定义

Package Dependencies

包依赖

Managing Dependencies

依赖管理

r
undefined
r
undefined

Use specific package functions with ::

Use specific package functions with ::

package::function()
package::function()

Add to DESCRIPTION Imports or Suggests

Add to DESCRIPTION Imports or Suggests

usethis::use_package("package_name") usethis::use_package("package_name", type = "Suggests")
undefined
usethis::use_package("package_name") usethis::use_package("package_name", type = "Suggests")
undefined

Common R Package Ecosystem Tools

常用R包生态工具

  • devtools: Development workflow
  • testthat: Testing framework
  • roxygen2: Documentation generation
  • usethis: Package setup automation
  • lintr: Code linting
  • styler: Code formatting
  • covr: Test coverage
  • pkgdown: Website generation
  • devtools:开发工作流工具
  • testthat:测试框架
  • roxygen2:文档生成工具
  • usethis:包设置自动化工具
  • lintr:代码规范检查工具
  • styler:代码格式化工具
  • covr:测试覆盖率工具
  • pkgdown:网站生成工具

When to Use This Skill

何时使用本技能

Activate this skill when:
  • Developing R packages
  • Writing R tests
  • Documenting R functions
  • Setting up R package infrastructure
  • Running R package checks
  • Working with devtools, testthat, or roxygen2
This skill provides R-specific development patterns. Project-specific architecture and domain knowledge should remain in project CLAUDE.md files.
在以下场景激活本技能:
  • 开发R包时
  • 编写R测试用例时
  • 编写R函数文档时
  • 搭建R包基础架构时
  • 运行R包检查时
  • 使用devtools、testthat或roxygen2时
本技能提供R语言专属的开发模式。 项目专属的架构和领域知识请保留在项目的CLAUDE.md文件中。