01 / 21

R Package
Structure

Learn how R packages are organized, what each file and folder does, and why understanding package structure makes you a better R programmer.

R Programming

What is an R Package?

An R package is a standardized collection of R code, data, documentation, and tests bundled together into a single, shareable unit. Think of it like a toolbox: each tool (function) has a specific purpose, and they are all organized in labeled compartments.

Why Packages Matter

Reusability
Write code once, use it in every project. No more copying and pasting functions between scripts.
Sharing
Publish to CRAN or GitHub so others can install your work with a single command.
Reliability
Built-in testing and documentation ensure your code works correctly and is well-explained.

The Big Picture: Package Anatomy

mypackage/ DESCRIPTION NAMESPACE R/ man/ tests/ Metadata Title, Author, Deps Export/Import Controls visibility R Code Your functions Documentation Help pages (.Rd) Tests Automated checks data/ vignettes/ inst/ src/ Bundled datasets Long-form guides Extra files C/C++ code Core Component Optional

The DESCRIPTION File

The DESCRIPTION file is the identity card of your package. It tells R (and the world) everything about who made it, what it does, and what it depends on.

Package: mypackage Title: A Brief Title for Your Package Version: 0.1.0 Authors@R: person("Jane", "Doe", email = "jane@example.com", role = c("aut", "cre")) Description: A longer description of what the package does. License: MIT + file LICENSE Imports: dplyr, ggplot2 Suggests: testthat

The R/ Directory

The R/ folder is where all your R source code lives. Every .R file inside this folder contains the functions that make your package useful.

One function per file
Best practice: name the file after the function it contains, like calculate_mean.R
No source() calls
R loads all files in R/ automatically. You never need source() inside a package.
# R/calculate_mean.R calculate_mean <- function(x) { if (!is.numeric(x)) { stop("x must be numeric") } sum(x) / length(x) }

The NAMESPACE File

The NAMESPACE file controls what goes in and out of your package. It determines which of your functions users can access, and which functions you borrow from other packages.

Your Package Internal helpers (hidden from users) Exported functions (users can call these) Imported functions (from other packages) export() Users see this import() From dplyr, etc.

man/ : Documentation

The man/ directory holds .Rd files: special documentation files that produce the help pages you see when you type ?function_name in R. These are generated from roxygen2 comments in your R code.

#' Calculate the mean of a numeric vector #' #' @param x A numeric vector #' @return A single numeric value #' @export #' @examples #' calculate_mean(c(1, 2, 3, 4, 5)) calculate_mean <- function(x) { sum(x) / length(x) }

tests/ : Automated Testing

The tests/ directory holds automated tests that verify your functions work correctly. The standard tool is the testthat package.

# tests/testthat/test-calculate_mean.R test_that("calculate_mean returns correct value", { expect_equal( calculate_mean(c(2, 4, 6)), 4 ) }) test_that("calculate_mean errors on non-numeric", { expect_error( calculate_mean("hello") ) })

Imports vs Suggests

Imports Suggests
When installed? Always (auto-installed) Only if user wants them
Used for? Core functionality Tests, vignettes, examples
If missing? Package fails to load Package still works
Example dplyr, ggplot2 testthat, knitr

Scripts vs Packages

R Script R Package
Structure Single .R file Organized directory tree
Loading source("file.R") library(pkg)
Documentation Comments (informal) Help pages (formal)
Testing Manual Automated (testthat)
Sharing Email/copy files install.packages()

How to Create a Package

1
Run usethis::create_package("mypackage") to scaffold the directory structure automatically.
2
Edit DESCRIPTION to add your name, title, and dependencies.
3
Write functions in R/ files with roxygen2 comments above each function.
4
Run devtools::document() to generate man/ pages and NAMESPACE from your roxygen comments.
5
Write tests in tests/testthat/ and run devtools::test() to verify everything works.
6
Run devtools::check() to ensure your package passes all CRAN-style checks.

Example: Minimal Package

Let us build a tiny package called greetR that has one function: say_hello().

greetR/ DESCRIPTION R/ NAMESPACE say_hello.R devtools::document() generates the NAMESPACE file
# R/say_hello.R #' Greet someone by name #' @param name A character string #' @return A greeting string #' @export say_hello <- function(name) { paste0("Hello, ", name, "!") }

Example: Adding Dependencies

Now we want greetR to use stringr for more advanced string operations. We need to declare it properly.

# In DESCRIPTION, add: Imports: stringr # In R/fancy_greet.R #' Create a fancy greeting #' @param name A character string #' @return A styled greeting #' @export fancy_greet <- function(name) { upper_name <- stringr::str_to_upper(name) paste0("Welcome, ", upper_name, "!") }

Example: The Full Workflow

Here is the complete sequence of commands to build, document, test, and check the greetR package from start to finish.

# Step 1: Create the package skeleton usethis::create_package("greetR") # Step 2: Add a function file usethis::use_r("say_hello") # Step 3: Set up testing usethis::use_testthat() usethis::use_test("say_hello") # Step 4: Generate docs + NAMESPACE devtools::document() # Step 5: Run tests devtools::test() # Step 6: Full check devtools::check()

Common Mistakes

✕ Using library() inside R/
Never call library() inside package code. Use the :: operator or declare imports in DESCRIPTION instead.
✕ Editing NAMESPACE by hand
Let roxygen2 manage NAMESPACE for you. Manual edits will be overwritten and cause errors.
✕ Forgetting @export
If you skip the @export roxygen tag, your function will not appear in NAMESPACE and users will not be able to call it.

Question 1 of 5

Which file serves as the "identity card" of an R package, containing its name, author, version, and dependencies?

Question 2 of 5

Where should you place your R function files inside a package?

Question 3 of 5

A package uses testthat only for running tests, not in its core functions. Where should testthat be listed in DESCRIPTION?

Question 4 of 5

What is the correct way to call a function from another package inside your own package code?

Question 5 of 5

Which roxygen2 tag must you include above a function definition to make it accessible to users of your package?