Function
Documentation in R
Learn to write clear, structured documentation for your R functions using comments and roxygen2-style tags so others (and future you) can understand your code.
Why Document Your Functions?
When you write a function in R, it might work perfectly today. But what about six months from now? What about when a classmate tries to use it? Documentation is the practice of adding structured descriptions to your code so that anyone can understand what a function does, what it expects, and what it returns.
Key Terms to Know
Plain Comments vs Roxygen Style
The Core Roxygen Tags
Anatomy of a Documented Function
Inline vs Block Comments
| Inline Comments | Roxygen Block | |
|---|---|---|
| Syntax | # comment | #' @tag text |
| Placement | Anywhere in code | Directly above function |
| Purpose | Explain how code works | Explain what function does |
| Machine-readable | No | Yes |
| Generates help? | No | Yes (via roxygen2) |
How to Write Documentation
Example 1: Simple Function
Example 2: Multiple Parameters
Example 3: Defaults and Edge Cases
Bonus Tags: @export and @import
How Roxygen Becomes a Help Page
Weak vs Strong Documentation
#' @param x the input
#' @return result
Vague, no types, no context. A reader learns almost nothing.
#' @param x numeric vector
#' @param threshold numeric. SD cutoff. Default 2.
#' @return numeric vector with outliers removed.
Specific, typed, default noted.
Common Mistakes
Tag Reference Summary
| Tag | Purpose | Required? |
|---|---|---|
| Title line | One-sentence summary | Yes |
| @description | Detailed explanation | Recommended |
| @param | Document each argument | Yes |
| @return | Describe return value | Yes |
| @examples | Show usage with code | Recommended |
| @export | Make public in package | Package only |
Question 1 of 5
What character sequence starts a roxygen-style documentation comment in R?
Question 2 of 5
Which roxygen tag is used to describe a function parameter?
Question 3 of 5
#' Calculate weighted average
#' @param values numeric vector of data points.
#' @param weights numeric vector of weights.
#' _______________
weighted_avg <- function(values, weights) {
sum(values * weights) / sum(weights)
}
Which line should fill the blank to complete this documentation?
Question 4 of 5
A classmate's @param line reads: #' @param x the input. What is the main problem?
Question 5 of 5
Where should roxygen documentation blocks be placed relative to the function they describe?