Create R Package
From Idea to Implementation
Creating an R package is a rewarding project that allows you to organize, share, and reuse your R code in a structured, efficient way. Whether you’re developing a library for personal use or preparing to share it with the broader R community, building a package will help you improve your coding practices and make your functions more portable and maintainable. In this blog post, we’ll walk through the essential steps of creating your first R package, from setting up the package structure to documenting your functions using roxygen2
.
1. Setting Up the Package Structure
Before you start coding, it’s essential to set up a proper package structure. The best way to get started is by using the devtools
package, which simplifies the process of creating, testing, and documenting your package.
Installing Required Packages
To begin, you need to install devtools
and usethis
—two powerful packages that help streamline package development.
r
Copy codeinstall.packages("devtools")
install.packages("usethis")
Once the packages are installed, load them into your session:
r
Copy codelibrary(devtools)
library(usethis)
Creating a New Package
To create a new package, use the create_package()
function from the usethis
package. This function sets up the basic directory structure for your package:
r
Copy code::create_package("path/to/your/package") usethis
This will create a new folder with the necessary subdirectories such as R/
, man/
, and DESCRIPTION
file. The R/
directory is where your R functions will go, and the man/
directory will hold the documentation files.
Package Structure Overview
- DESCRIPTION: Contains metadata about your package, such as name, version, description, dependencies, and authorship.
- R/: This folder contains the R code for the package (i.e., your functions).
- man/: This folder contains documentation files for each function in the package.
- NAMESPACE: Defines the functions that are exported by your package.
- tests/: (optional) Contains tests for your functions, typically using the
testthat
package.
The basic structure after running create_package()
should look like this:
go
Copy code-package/
your
├── DESCRIPTION
├── NAMESPACE/
├── R.R
│ └── your_function/
└── man.Rd └── your_function
2. Writing Functions for Your Package
Now that your package structure is set up, you can start writing functions. Let’s create a simple function for demonstration purposes.
Writing the First Function
Inside the R/
folder, create a new R file called add_numbers.R
and write your first function. For example, a function to add two numbers:
r
Copy code#' Add two numbers
#'
#' This function takes two numeric values and returns their sum.
#'
#' @param x A numeric value.
#' @param y A numeric value.
#' @return The sum of \code{x} and \code{y}.
#' @export
<- function(x, y) {
add_numbers return(x + y)
}
In this code:
- The
@param
tags describe the function’s arguments. - The
@return
tag explains what the function returns. - The
@export
tag marks this function for export, making it accessible to users of your package.
Saving the Function
Save the file in the R/
directory with a .R
extension (e.g., add_numbers.R
). You can add more functions in the same directory, each function stored in its own file or grouped together in a single file, depending on their functionality.
3. Documenting Functions with roxygen2
Documenting your functions properly is an important aspect of creating a package. The roxygen2
package provides a streamlined way to generate documentation for your functions directly from the comments in your R code.
Installing and Using roxygen2
First, install the roxygen2
package if you haven’t already:
r
Copy codeinstall.packages("roxygen2")
Next, load the package:
r
Copy codelibrary(roxygen2)
Documenting with roxygen2
Notice in the function we created earlier, we included special comments above the function. These comments follow the roxygen2
syntax. Here’s a breakdown of the key elements:
@param
: Describes the arguments of the function.@return
: Describes the output of the function.@export
: Marks the function for export so that it becomes available to users of the package.@examples
: Provides example usage of the function.
To generate the documentation files, you will run the roxygen2::roxygenize()
function. This will read your function files, extract the comments, and automatically generate .Rd
files in the man/
directory, which R uses for help files.
r
Copy code::roxygenize("path/to/your/package") roxygen2
This command will create a .Rd
file for each function in the man/
directory. For example, the add_numbers
function will have an associated add_numbers.Rd
file in the man/
directory, which can be accessed via the help()
function in R:
r
Copy codehelp(add_numbers)
NAMESPACE and Exporting Functions
roxygen2
also helps manage your NAMESPACE
file. When you use the @export
tag in your function’s documentation, roxygen2
automatically updates the NAMESPACE
file to export that function.
For instance, after running roxygen2::roxygenize()
, your NAMESPACE
file will include a line like this:
scss
Copy code export(add_numbers)
This tells R that add_numbers
should be available for users of the package.
4. Testing Your Package
Before distributing your package, it’s important to test it to ensure that everything works as expected. You can use the testthat
package for unit testing.
Setting Up Tests with testthat
First, install testthat
if you haven’t already:
r
Copy codeinstall.packages("testthat")
To set up tests, create a tests/testthat/
folder in your package directory. Inside, create a file like test-add_numbers.R
and write tests for your function:
r
Copy codetest_that("add_numbers adds correctly", {
expect_equal(add_numbers(2, 3), 5)
expect_equal(add_numbers(-1, 1), 0)
expect_equal(add_numbers(0, 0), 0)
})
Then, you can run the tests using the following command:
r
Copy code::test() devtools
This will run all tests in the tests/testthat/
folder and check that your package functions as expected.
5. Building and Installing Your Package
Once you have written your functions and documented them, it’s time to build and install your package.
Building the Package
To build your package into a .tar.gz
file, use the following command:
r
Copy code::build("path/to/your/package") devtools
Installing the Package
To install your package locally for testing, run:
r
Copy code::install("path/to/your/package") devtools
You can now load your package and use it like any other R package:
r
Copy codelibrary(yourPackageName)
add_numbers(1, 2)
Conclusion
Creating an R package is an essential skill for any advanced R user, as it allows you to organize and share your code effectively. In this post, we’ve covered the key steps to building your first R package—from setting up the package structure and writing functions to documenting them using roxygen2
and testing with testthat
.