The minimal R package
Let’s start with a simple example: a directory with 2 R files.
brocolors.Rdefines a function
brocolors()that gives vectors of colors that I like to use in figures, including a vector of crayon colors.
plot_crayons.Rdefines a function
plot_crayons()for making a plot illustrating the crayon colors.
To make this code into an R package, we just need to do two things:
- Create an
Rsubdirectory and move the code into that subdirectory.
Create a text file called
DESCRIPTIONcontaining the following:
Package: brocolors Version: 0.1
That is, you just need to give the package a name, like
brocolors, and a
version number, like
0.1, and then put those pieces in a
DESCRIPTION in this specific way.
Believe it or not, that’s all you need to have a working R package!
Note that the R code can be all in one file or split across many files
(e.g., you could have one function in each file, as here). I’d
suggest leaning towards many small files. A
util.R file is unwieldy.
It’s not a proper R package. You need to fill out the
file a bit and add some documentation. (Also, you need a
file; more on that soon.) But those two steps alone are
sufficient for you to build and install the package – for your
own use, or to be shared with a friend.
Note: usually the directory containing this stuff would be named
with the package name (
brocolors in this case). This isn’t strictly
necessary, but it’s confusing otherwise.
In my example,
I’m making several different versions of the package
directory, to illustrate the process of going from a minimal package
to a proper package to a fully filled-out package. And so I’m calling
etc., even though this would really just be a single directory,
brocolors, being modified over time.
A few asides
The functions above are taken from my R/broman package, which contains miscellaneous R functions that are useful to me.
Alyssa Frazee’s RSkittleBrewer package inspired me to write these functions. It’s made it a lot easier for me to define colors for graphs I make for lectures and papers. (For a really useful R color package see, Karthik Ram’s wesanderson package.)
Regarding version numbers: I number things like
major.minor-revision as I learned from Venables and Ripley’s
Yihui Xie recommends
major.minor.patch, but having releases be
major.minor. You should probably follow
Now, take a couple of your own R functions
- make a directory for them
- create an
- put your R functions into one or more
.Rfiles within the
- write a minimal
Then go to the page about building and installing an R package.