Creating a Custom R Package. Create a central location for all your... | by Dick Brown | Towards Data Science

I don’t know about you, but I find the method that R uses to sort data frames incredibly non-intuitive. Every time I want to sort a data frame, I have to puzzle through how to do it, usually by looking up online how somebody else did it, then copying and modifying their code. Finally, I decided to create an easy-to-use function that could sort data frames for me. Here’s the latest version of the function that I came up with:
sortby <- function(df, col, desc = FALSE) {    #### df is the dataframe to be sorted    #### col is the variable by which it should be sorted    #### desc indicates whether the sort order should be descending    #### str2expression() allows us to dynamically create a df$col    ####     variable which gets evaluated by eval()    df[order(            eval(                str2expression(paste0("df$", col))             ),             decreasing = desc        ),]}
The problem I had then was how to find the function when I want to use it. The answer was to create my very own package. Now, there are a lot of tutorials out there on how to create R packages, but they all lacked something. Some were incomplete or broken up into multiple pages. Some were confusing. Some were out-of-date. The purpose of this article is to detail, from start to finish, the process I came up with by combining many of those tutorials.
First, I should mention that I use RStudio for all of my R programming. One of my requirements, then, is that it must be doable within that environment. While none of the tutorials actually exclude the use of RStudio, many of them ignore it altogether.
The process of creating a usable package in R has several parts:
Write the function(s) to include in the package.
Create the documentation for the function(s) in the package.
Build the package.
(Optional, and not covered here) Publish the package.
The first step is covered above with my sortby() function. I stored this function in a script called sortby.R.
Before we go any further, there’s some setup we need to do. To create R packages in Windows, you need to install RTools 4.0. This is installed as a normal Windows program, rather than as a package in R. you can find the installation program at https://cran.r-project.org/bin/windows/Rtools/. I should say that I had issues trying to get RTools to work. The installation went fine, but the setup went awry. When I created the .Renviron file to edit the path, I could no longer install packages. I tried a few things, including resetting Windows. After a lot of research, I found that somebody mentioned running R as admin before trying to install a package. This seemed to fix everything, and I don’t need to run as admin any more.
Once RTools is set up, you can go about creating the package. In RStudio, select File > New Project > New Directory > R Package. In the dialog box that pops up, give the package a name and enter the directory in which you want the package to reside. If you’ve already created the R script, as I did, you can add that to the package at this point by adding it to the box under “Create package based on source files:”.
Then click on <Create Project>.
At this point, you should see a “Build” tab somewhere. I have it next to my “History” tab at the bottom left. (I believe that the default is in the top right window.) Select the Build tab, and click on “Install and Restart” to install your package. Once you’ve done that, the package should show up in your “Packages” tab as shown below.
Note that the description of the package still says “What the Package Does (Title Case)”. We’ll fix that in a bit. Next, look at the “Files” tab. You’ll see a bunch of files and directories that RStudio created for your project. The script files will be in the “R” directory and the help files will be in the “man” directory.
To fix the description issue above, open the DESCRIPTION file. This required file stores metadata about the package.
For now, let’s just change the obvious stuff. If your package has any dependencies (like dplyr, etc.), that should be included in this file, but it’s not part of the default setup.
I’ve edited the Title, Author, and Description lines, and removed the Maintainer line. Note that the Title line became the description in the package list in the bottom right window.
The easiest way to create a help file is to use the roxygen2 package.
install.packages("roxygen2")library(roxygen2)
Now, we go to the R script and add some roxygen comments to the beginning. Each oxygen comment line begins with #’. There are several items that you should add:
#' @title #' @description#' @param#' @return#' @example#' @examples
Title — used to add a title to the help page (use title case)
Description — used to add a short description
Param — Add one of these lines for each parameter to your function
Return — What the function will give you
Example/Examples — Add one or more lines of examples. Use the plural if you’re adding more than one line of examples. Double-check these examples before finishing, to make sure no errors crept in while you weren’t looking.
Once you’ve finished adding the roxygen comments, run the following command:
roxygenize()
(As usual, R allows for either the American English or British English version of the command, so roxygenise() works just as well.)
This command creates the .Rd file in the man folder. The .RD file is what’s used to create the actual help file. My final R script and the help file that is generated are shown below.
That’s it for the basics of creating an R package. There’s a lot more fine-tuning you can do, especially if you want to publish your package. For a lot more information on package creation, check out Hadley Wickham’s book R Packages at https://r-pkgs.org/.