![](https://static.isu.pub/fe/default-story-images/news.jpg?width=720&quality=85%2C50)
2 minute read
Version Control and Repositories ���������������������������������������������������������������������������������
CHAPTER 11
Building an R Package
Advertisement
You now know how to write functions and create classes in R, but neither functions nor classes is the unit you use for collecting and distributing R code. That unit is the package. It is packages that you load and import into your namespace when you write this:
library(something)
And it is packages you download when you write this:
install.packages("something")
The topic of this chapter is how to make your own packages. In the space available, I can only give a very broad overview of the structure of R packages, but it should be enough to get you started. If you want to read more, I warmly recommend Hadley Wickham’s book R Packages.
Creating an R Package
I am going to assume that you use RStudio for this. If you don’t, you can look at the devtools package. It provides functions for doing everything you can do through the GUI in RStudio.
To create a new package, choose File ➤ New Project and you should get a dialog box that asks you whether your new project should be in a new director, in an existing directory, or checked out of a version control repository. Pick the New Directory.
After that, you get the choice between an empty project, a package, or a shiny application. Not surprisingly, you want to pick R Package.
Now you get to a dialog box where you can set the details of the package. You can choose the Type of the package (where you can choose between a plain package or one that uses Rcpp to make C++ extensions); you can specify the Name of the package; and you can provide existing source files to include in the package. Further, you need to choose a location to put the new package and whether you want to use a git repository for the package.
Choose a plain package and click Yes to create a git repository (we return to git later). You now just need to pick a name and a place to put your package. Where you put it is up to you, but there are some guidelines for package names, discussed next.
Package Names
A package name can consist of letters, numbers, and ., but must start with a letter and must not have . as the last character. You cannot use other characters, such as underscores or dashes.