How to write an R package


When you see “R package,” you may think “Something to share with other people.” But an R package can also be a good way to organize your own work just for yourself. And especially your future self.

R packages give you a consistent structure, so you’re more likely to refactor code into functions. And, at least as important: Packages give you a consistent way to document each one of your functions. So, next year, there’s a better chance you’ll remember which parts of your code do what.

System setup

First, you want to set up your system. For easy package development, I suggest making sure you’ve got these libraries installed on your system: devtools, usethis, roxygen2, testthat, knitr, and rmarkdown.

You probably need a little more system setup as well. In Windows, install software called . That’s actually a software application, not an R package. On a Mac, it is helpful to get from the App Store.

If you’re not sure whether your system is ready to write packages, devtools has a function called has_devel() that checks if your package development environment is OK. I suggest running that after you’ve got devtools installed.

Sharon Machlis/IDG

Creating a new package in RStudio

Next, you can create a new package in RStudio by going to File > New Project > New Directory and choosing R Package.

.” And Hadley Wickham has an entire book on writing packages, available free online at , though it’s a bit out of date now. Jenny Bryan at RStudio is working with Wickham on an update. You can see a bit of the work in progress at .