write-roxygen-docs

Write roxygen2 documentation for R package functions, datasets, and classes. Covers all standard tags, cross-references, examples, and generating NAMESPACE entries. Follows tidyverse documentation style. Use when adding documentation to new exported functions, documenting internal helpers or datasets, documenting S3/S4/R6 classes and methods, or fixing documentation-related R CMD check notes.

9 stars

Best use case

write-roxygen-docs is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Write roxygen2 documentation for R package functions, datasets, and classes. Covers all standard tags, cross-references, examples, and generating NAMESPACE entries. Follows tidyverse documentation style. Use when adding documentation to new exported functions, documenting internal helpers or datasets, documenting S3/S4/R6 classes and methods, or fixing documentation-related R CMD check notes.

Teams using write-roxygen-docs should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/write-roxygen-docs/SKILL.md --create-dirs "https://raw.githubusercontent.com/pjt222/agent-almanac/main/i18n/caveman-lite/skills/write-roxygen-docs/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/write-roxygen-docs/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How write-roxygen-docs Compares

Feature / Agentwrite-roxygen-docsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Write roxygen2 documentation for R package functions, datasets, and classes. Covers all standard tags, cross-references, examples, and generating NAMESPACE entries. Follows tidyverse documentation style. Use when adding documentation to new exported functions, documenting internal helpers or datasets, documenting S3/S4/R6 classes and methods, or fixing documentation-related R CMD check notes.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Write Roxygen Documentation

Create complete roxygen2 documentation for R package functions, datasets, and classes.

## When to Use

- Adding documentation to a new exported function
- Documenting internal helper functions
- Documenting package datasets
- Documenting S3/S4/R6 classes and methods
- Fixing documentation-related `R CMD check` notes

## Inputs

- **Required**: R function, dataset, or class to document
- **Optional**: Related functions for cross-referencing (`@family`, `@seealso`)
- **Optional**: Whether the function should be exported

## Procedure

### Step 1: Write Function Documentation

Place roxygen comments directly above the function:

```r
#' Compute the weighted mean of a numeric vector
#'
#' Calculates the arithmetic mean of `x` weighted by `w`. Missing values
#' in either `x` or `w` are handled according to the `na.rm` parameter.
#'
#' @param x A numeric vector of values.
#' @param w A numeric vector of weights, same length as `x`.
#' @param na.rm Logical. Should missing values be removed? Default `FALSE`.
#'
#' @return A single numeric value representing the weighted mean.
#'
#' @examples
#' weighted_mean(1:5, rep(1, 5))
#' weighted_mean(c(1, 2, NA, 4), c(1, 1, 1, 1), na.rm = TRUE)
#'
#' @export
#' @family summary functions
#' @seealso [stats::weighted.mean()] for the base R equivalent
weighted_mean <- function(x, w, na.rm = FALSE) {
  # implementation
}
```

**Got:** Complete roxygen block with title, description, `@param` for each parameter, `@return`, `@examples`, and `@export`.

**If fail:** If unsure about a tag, check `?roxygen2::rd_roclet`. Common omission is `@return`, which is required by CRAN for all exported functions.

### Step 2: Essential Tags Reference

| Tag | Purpose | Required for export? |
|-----|---------|---------------------|
| `#' Title` | First line, one sentence | Yes |
| `#' Description` | Paragraph after blank line | Yes |
| `@param` | Parameter documentation | Yes |
| `@return` | Return value description | Yes (CRAN) |
| `@examples` | Usage examples | Strongly recommended |
| `@export` | Add to NAMESPACE | Yes, for public API |
| `@family` | Group related functions | Recommended |
| `@seealso` | Cross-references | Optional |
| `@keywords internal` | Mark as internal | For non-exported docs |

**Got:** All required tags for the function type are identified. Exported functions have `@param`, `@return`, `@examples`, and `@export` at minimum.

**If fail:** If a tag is unfamiliar, consult the [roxygen2 documentation](https://roxygen2.r-lib.org/articles/rd.html) for usage and syntax.

### Step 3: Document Datasets

Create `R/data.R`:

```r
#' Example dataset of city temperatures
#'
#' A dataset containing daily temperature readings for major cities.
#'
#' @format A data frame with 365 rows and 4 variables:
#' \describe{
#'   \item{date}{Date of observation}
#'   \item{city}{City name}
#'   \item{temp_c}{Temperature in Celsius}
#'   \item{humidity}{Relative humidity percentage}
#' }
#' @source \url{https://example.com/data}
"city_temperatures"
```

**Got:** `R/data.R` contains roxygen blocks for each dataset with `@format` describing the structure and `@source` providing data provenance.

**If fail:** If `R CMD check` warns about undocumented datasets, ensure the quoted string (e.g., `"city_temperatures"`) exactly matches the object name saved with `usethis::use_data()`.

### Step 4: Document the Package

Create `R/packagename-package.R`:

```r
#' @keywords internal
"_PACKAGE"

## usethis namespace: start
## usethis namespace: end
NULL
```

**Got:** `R/packagename-package.R` exists with `@keywords internal` and the `"_PACKAGE"` sentinel. Running `devtools::document()` generates `man/packagename-package.Rd`.

**If fail:** If `R CMD check` reports a missing package documentation page, verify the file is named `R/<packagename>-package.R` and contains the `"_PACKAGE"` string.

### Step 5: Handle Special Cases

**Functions with dots in names** (S3 methods):

```r
#' @export
#' @rdname process
process.myclass <- function(x, ...) {
  # S3 method
}
```

**Reusing documentation** with `@inheritParams`:

```r
#' @inheritParams weighted_mean
#' @param trim Fraction of observations to trim.
trimmed_mean <- function(x, w, na.rm = FALSE, trim = 0.1) {
  # implementation
}
```

**No visible binding fix** using `.data` pronoun:

```r
#' @importFrom rlang .data
my_function <- function(df) {
  dplyr::filter(df, .data$column > 5)
}
```

**Got:** Special cases (S3 methods, inherited params, `.data` pronoun) are documented correctly. `@rdname` groups S3 methods together. `@inheritParams` reuses parameter docs without duplication.

**If fail:** If `R CMD check` warns about "no visible binding for global variable," add `#' @importFrom rlang .data` or use `utils::globalVariables()` as a last resort.

### Step 6: Generate Documentation

```r
devtools::document()
```

**Got:** `man/` directory updated with `.Rd` files for each documented object. `NAMESPACE` regenerated with correct exports and imports.

**If fail:** Check for roxygen syntax errors. Common issues: unclosed brackets in `\describe{}`, missing `#'` prefix on a line, or invalid tag names. Run `devtools::document()` again after fixing.

## Validation

- [ ] Every exported function has `@param`, `@return`, and `@examples`
- [ ] `devtools::document()` runs without errors
- [ ] `devtools::check()` shows no documentation warnings
- [ ] `@family` tags group related functions correctly
- [ ] Examples run without errors (test with `devtools::run_examples()`)

## Pitfalls

- **Missing `@return`**: CRAN requires all exported functions to document their return value
- **Examples that need internet/auth**: Wrap in `\dontrun{}` with a comment explaining why
- **Slow examples**: Use `\donttest{}` for examples that work but take too long for CRAN
- **Markdown in roxygen**: Enable with `Roxygen: list(markdown = TRUE)` in DESCRIPTION
- **Forgetting to run `devtools::document()`**: Man pages are generated, not hand-written

## Related Skills

- `create-r-package` - initial package setup including roxygen configuration
- `write-testthat-tests` - test the functions you document
- `write-vignette` - long-form documentation beyond function reference
- `submit-to-cran` - documentation requirements for CRAN

Related Skills

write-vignette

9
from pjt222/agent-almanac

Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.

write-validation-documentation

9
from pjt222/agent-almanac

Write IQ/OQ/PQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.

write-testthat-tests

9
from pjt222/agent-almanac

Write comprehensive testthat (edition 3) tests for R package functions. Covers test organization, expectations, fixtures, mocking, snapshot tests, parameterized tests, and achieving high coverage. Use when adding tests for new package functions, increasing test coverage for existing code, writing regression tests for bug fixes, or setting up test infrastructure for a package that lacks it.

write-standard-operating-procedure

9
from pjt222/agent-almanac

Write a GxP-compliant Standard Operating Procedure (SOP). Covers regulatory SOP template structure (purpose, scope, definitions, responsibilities, procedure, references, revision history), approval workflow design, periodic review scheduling, and operational procedures for system use. Use when a new validated system requires operational procedures, when existing informal procedures need formalisation, when an audit finding cites missing procedures, when a change control triggers SOP updates, or when periodic review identifies outdated procedural content.

write-incident-runbook

9
from pjt222/agent-almanac

Create structured incident runbooks with diagnostic steps, resolution procedures, escalation paths, and communication templates for effective incident response. Use when documenting response procedures for recurring alerts, standardizing incident response across an on-call rotation, reducing MTTR with clear diagnostic steps, creating training materials for new team members, or linking alert annotations directly to resolution procedures.

write-helm-chart

9
from pjt222/agent-almanac

Create production-ready Helm charts for Kubernetes application deployment with templating, values management, chart dependencies, hooks, and testing. Covers chart structure, Go template syntax, values.yaml design, chart repositories, versioning, and best practices for maintainable and reusable charts. Use when packaging a Kubernetes application for repeatable deployments, parameterizing manifests for multiple environments, managing complex multi-component applications with dependencies, or standardizing deployment practices with versioned rollback capability across teams.

write-continue-here

9
from pjt222/agent-almanac

Write a CONTINUE_HERE.md file capturing current session state so a fresh Claude Code session can pick up where this one left off. Covers assessing recent work, structuring the continuation file with objective, completed, in-progress, next-steps, and context sections, and verifying the file is actionable. Use when ending a session with unfinished work, handing off context between sessions, or preserving task state that git alone cannot capture.

write-claude-md

9
from pjt222/agent-almanac

Create an effective CLAUDE.md file that provides project-specific instructions to AI coding assistants. Covers structure, common sections, do/don't patterns, and integration with MCP servers and agent definitions. Use when starting a new project where AI assistants will be used, improving AI behavior on an existing project, documenting project conventions and constraints, or integrating MCP servers or agent definitions into a project workflow.

skill-name-here

9
from pjt222/agent-almanac

One to three sentences describing what this skill accomplishes, followed by key activation triggers. This field is the primary mechanism agents use to decide whether to activate the skill — it is read during discovery before the full body is loaded. Start with a verb. Include the most important "when to use" conditions inline. Max 1024 characters.

vishnu-bhaga

9
from pjt222/agent-almanac

Preservation and sustenance — maintaining working state under perturbation, memory anchoring, consistency enforcement, and protective stabilization. Maps Vishnu's sustaining presence to AI reasoning: holding what works steady, anchoring verified knowledge against drift, and ensuring continuity through change. Use when a working approach is at risk from scope creep, when context drift threatens verified knowledge, after shiva-bhaga dissolution to protect what survived, when a long session risks losing earlier decisions through context compression, or before making changes to a currently functioning system.

version-ml-data

9
from pjt222/agent-almanac

Version machine learning datasets using DVC (Data Version Control) with remote storage backends, build reproducible data pipelines with dependency tracking, integrate with Git workflows, and ensure data lineage for model reproducibility. Use when versioning large datasets that do not fit in Git, tracking data changes alongside code changes, ensuring ML experiment reproducibility, sharing datasets across team members, or auditing data lineage for compliance requirements.

verify-agent-output

9
from pjt222/agent-almanac

Validate deliverables and build evidence trails when work passes between agents. Covers expected outcome specification before execution, structured evidence generation during execution, deliverable validation against external anchors after execution, fidelity checks for compressed or summarized outputs, trust boundary classification, and structured disagreement reporting on verification failure. Use when coordinating multi-agent workflows, reviewing cross-agent handoffs, producing external-facing outputs, or auditing whether an agent's summary faithfully represents its source material.