This tutorial will take you through the steps of creating a new package in R.
There are five primary tasks:
It is recommended to complete this lab in a regular R console, NOT in R Studio. You can do it using RMD docs as well, but some of the steps will be different and it complicates things.
The five steps are explained below, but the entire script you will need will look something like this:
# set your working directory
# if you don't want to create
# the package in your default
# working directory
getwd() # default directory, usually my documents
library(devtools)
# step 1
::create_package( "montyhall" )
usethis
# step 2 move R script to montyhall/R folder
# after completing documentation fields
# step 3
setwd( "montyhall" )
::document()
devtools
# step 4
setwd( ".." )
::install( "montyhall" )
devtoolslibrary( montyhall )
create_game()
# step 5: close R and re-open new console
::install_github( "yourGitHubName/montyhall" ) devtools
Note, if you make a mistake or encounter an error delete the new montyhall folder before starting over.
You will need to download the Monty Hall Problem functions that we completed during Labs 01 and 02 from the link below. This script contains some roxygen text to get you started with the process of documentation.
DOWNLOAD THE TEMPLATE: monty-hall-problem.R
Note that you will update this script and place it in the montyhall/R folder after you complete Step 01 and the package skeleton has been created (the working directories for your package are built).
The package code is provided - you just need to complete the documentation and develop the test code for each function (you can adapt these from the unit testing examples in the labs).
After completing documentation will place the template file monty-hall-problem.R directly in the R folder. You should not be using RMD files in this assignment.
install.packages(c("devtools", "roxygen2","usethis","testthat","knitr"))
# if devtools is not working try
# devtools::build_github_devtools()
You can check that you have everything installed and working by running the following code:
library(devtools)
has_devel()
## Your system is ready to build packages!
# set your directory if you want the package
# created in a folder other than the default "documents"
setwd( "some/path/here" )
# devtools::create_package() has been deprecated
::create_package( "montyhall" ) usethis
This example is using the default “documents” directory:
getwd() # documents in this example
usethis::create_package( "montyhall" )
documents # package created inside documents
├─ montyhall # new folder that will appear after create_package()
│ ├─ R
What you should see:
# > usethis::create_package( "montyhall" )
# ✔ Creating 'montyhall/'
# ✔ Setting active project to 'C:/Users/jdlecy/Documents/montyhall'
# ✔ Creating 'R/'
# ✔ Writing 'DESCRIPTION'
# Package: montyhall
# Title: What the Package Does (One Line, Title Case)
# Version: 0.0.0.9000
# Authors@R (parsed):
# * First Last <first.last@example.com> [aut, cre] (<https://orcid.org/YOUR-ORCID-ID>)
# Description: What the package does (one paragraph).
# License: What license it uses
# Encoding: UTF-8
# LazyData: true
# ✔ Writing 'NAMESPACE'
# ✔ Writing 'montyhall.Rproj'
# ✔ Adding '.Rproj.user' to '.gitignore'
# ✔ Adding '^montyhall\\.Rproj$', '^\\.Rproj\\.user$' to '.Rbuildignore'
# ✔ Opening 'montyhall/' in new RStudio session
# ✔ Setting active project to '<no active project>'
You will now have a directory in your current folder called montyhall. This will contain the files you need for your package.
Note, some of these files like gitignore are from GitHub - they will appear after completing Step 05. Files may vary by operating system, but you should at the very least have the R folder, a DESCRIPTION file, and a NAMESPACE file.
Add your roxygen comments to your R scripts:
#' @title
#' Sum of vector elements.
#'
#' @description
#' `sum(x)` returns the sum of all the values present in its arguments.
#'
#' @details
#' This is a generic function: methods can be defined for it directly
#' or via the [Summary] group generic. For this to work properly,
#' the arguments `...` should be unnamed, and dispatch is on the
#' first argument.
#'
#' @param x Numeric, complex, or logical vectors.
#' @param na.rm A logical scalar. Should missing values (including `NaN`)
#' be removed?
#' @return If all inputs are integer and logical, then the output
#' will be an integer. Otherwise it will be a length-one numeric or
#' complex vector.
#'
#' Zero-length vectors have sum 0 by definition. See
#' <http://en.wikipedia.org/wiki/Empty_sum> for more details.
#'
#' @examples
#' sum(1:10)
#' sum(1:5, 6:10)
#' sum(F, F, F, T, T)
#'
#' sum(.Machine$integer.max, 1L)
#' sum(.Machine$integer.max, 1)
#'
#' \dontrun{
#' sum("a")
#' }
<- function(..., na.rm = TRUE) {} sum
Note that good documentation describes all of the arguments needed by the function, including the required data types of each object. And clearly describe what will be returned when the function runs (type of object, what it contains). Roxygen, unlike R, is sensitive to the number of spaces your use. So don’t alter the formatting of the default comments in your script.
Place your documented R scripts into the “R” folder in your package directory, then try:
setwd( "montyhall" )
getwd() # 'C:/Users/username/Documents/montyhall'
::document() devtools
documents
├─ montyhall # should be inside here now
│ ├─ R # your R scripts should be in here
You should see:
# Updating montyhall documentation
# Updating roxygen version in C:\Users\jdlecy\Documents\montyhall/DESCRIPTION
# Writing NAMESPACE
# Loading montyhall
# Writing create_game.Rd
documents
├─ montyhall
│ ├─ R
│ ├─ man # new *.rd files will be here
You will see some errors as well if you have not yet finished documenting your functions. Ignore them for now.
Depending upon your OS and your R devtools version you may be required to complete ALL documentation before preceding to the next steps. At the very least each function should have a title.
You will now have a new folder in your montyhall directory called “man”, short for “manuals”. The documentation files have an .Rd (R documentation) extension. The man folder should contain one .Rd file for each exported function in your script (change_door.Rd, create_game.Rd, etc.).
Skip to the testing step below if you want to see if the package is now functional.
Navigate to the main “montyhall” package folder on your computer and open the file called “DESCRIPTION” in a text editor (your computer will have a text editor like notebook). You will see something like this:
: montyhall
Package: What the Package Does (One Line, Title Case)
Title: 0.0.0.9000
Version@R:
Authorsperson(given = "First",
family = "Last",
role = c("aut", "cre"),
email = "first.last@example.com",
comment = c(ORCID = "YOUR-ORCID-ID"))
: What the package does (one paragraph).
Description: What license it uses
License: UTF-8
Encoding: true
LazyData: 6.1.1 RoxygenNote
Since we use dplyr in the package, we need to add another line to import and attach it. Add:
Depends:
dplyr
Now complete the rest of the fields from “Title” to “Description”.
: montyhall
Package: What the Package Does (One Line, Title Case)
Title: 0.0.0.9000
Version@R:
Authorsperson(given = "First",
family = "Last",
role = c("aut", "cre"),
email = "first.last@example.com",
comment = c(ORCID = "YOUR-ORCID-ID"))
: What the package does (one paragraph).
Description:
Depends
dplyr: What license it uses
License: UTF-8
Encoding: true
LazyData: 6.1.1 RoxygenNote
Go up one level in your directory so you are outside of the package folder, but in the same folder where the package folder lives.
documents # should be back here
├─ montyhall
│ ├─ R
│ ├─ man # new *.rd files will be here
Then run the command to install your new package.
The install() command is looking for a folder called “montyhall”. It can’t find the folder if we are currently inside the folder. Thus we move up one level in the directory first:
setwd( ".." ) # move up one level with two periods
getwd() # should be /documents NOT /montyhall
::install( "montyhall" ) devtools
If successful you will see messages like this:
# Updating montyhall documentation
# Updating roxygen version in C:\Users\jdlecy\Documents\montyhall/DESCRIPTION
# Writing NAMESPACE
# Loading montyhall
# Writing create_game.Rd
# > getwd()
# [1] "C:/Users/jdlecy/Documents/montyhall"
# > setwd( ".." )
# > devtools::install( "montyhall" )
# √ checking for file 'C:\Users\jdlecy\Documents\montyhall/DESCRIPTION'
# - preparing 'montyhall':
# √ checking DESCRIPTION meta-information ...
# - checking for LF line-endings in source and make files and shell scripts
# - checking for empty or unneeded directories
# - building 'montyhall_0.0.0.9000.tar.gz'
#
# Running "C:/PROGRA~1/R/R-36~1.1/bin/x64/Rcmd.exe" INSTALL \
# "C:\Users\jdlecy\AppData\Local\Temp\RtmpKetkbm/montyhall_0.0.0.9000.tar.gz" --install-tests
# * installing to library 'C:/Users/jdlecy/Documents/R/win-library/3.6'
# * installing *source* package 'montyhall' ...
# ** using staged installation
# ** R
# ** byte-compile and prepare package for lazy loading
# ** help
# *** installing help indices
# 'montyhall'g help for package finding HTML links ...
# done
# -reate_game html
# ** building package indices
# ** testing if installed package can be loaded from temporary location
# *** arch - i386
# *** arch - x64
# ** testing if installed package can be loaded from final location
# *** arch - i386
# *** arch - x64
# ** testing if installed package keeps a record of temporary installation path
# * DONE (montyhall)
In a new R session try:
library( montyhall )
create_game()
## [1] "goat" "car" "goat"
You should be able to preview the help files that you created with your roxygen comments.
help( "create_game" )
If you encounter an error or the package is not working properly, you might need to fix your code and try again.
You should be able to update the package then simply reinstall it. R will recognize that there are changes to the package and will install the most recent version.
If you run into problems you can force a package deletion then install fresh.
# library() attaches the package to the current environment
# detach is the opposite of library() - closes the package
detach( "package:montyhall" ) # closes the package so not locked
remove.packages( "montyhall" ) # deletes from your computer
If that fails, you probably have the package loaded in another R session or have package files locked by editing them in another program.
If all else fails, you can delete the package manually from your personal R packages library, which usually lives in your Documents folder.
These are a few good resources for reference:
A nice tutorial by Fong Chun Chan
The official R Packages book by Hadley Wickham and Jenny Bryant