library(usethis)
# I'm using a temp folder, but you should use something else like
# "C:/Users/vegayon/Documents/boringpkg"
tmp_folder <- tempfile("boringpkg")
# Creating the package
usethis::create_package(
path = tmp_folder,
roxygen = TRUE, # Docs and NAMESPACE are generated from roxygen2 comments
rstudio = TRUE, # Adds an .Rproj file so you can open it as an RStudio project
fields = list( # Values written to the DESCRIPTION file
Package = "boringpkg",
Version = "0.0.0.9000",
Title = "A boring package",
Description = "A boring package"
)
)
# We can inspect what things it created:
list.files(tmp_folder, recursive = TRUE)Building R packages (part I)
PHS 7045: Advanced Programming
Intro
Today
Have a look at some R-package-dev practices.
We won’t discuss either Rcpp or coding R itself. (for that I recommend “Advance R”, and there’s also Patrick Muchmore’s “A template for R packages using Rcpp and/or RcppArmadillo”)
We won’t discuss GitHub in depth. I’ll assume that the user already knows the basics of Git(Hub): Creating a repo online and start using it locally. (A good reference is “Pro Git” and “Happy Git and GitHub for the useR”)
We won’t discuss software engineering/design; we’ll look at some tools and dev cycles. (For that, you have “CodeComplete”)
What we’ll be using today
devtools: “Package development tools for R” (read more).
roxygen2: “A ‘Doxygen’-like in-source documentation system for Rd, collation, and ‘NAMESPACE’ files” (read more).
covr: (An R package for) “Test Coverage for Packages” (read more).
RStudio: “RStudio is an integrated development environment (IDE) for R” (read more).
valgrind: (if you use C/C++ code) “a memory error detector” (read more).
Why ‘spend’ time writing an R package?
To name a few:
Easy way to share code: Type
install.packagesand voila!Already standardized: So you don’t need to think about how to structure it.
CRAN checks everything for you: Force yourself to code things right.
Reproducible Research
Accessible Reproducible Research (Mesirov, Science 2010)
Again, and Again, and Again, … (Jasny et al., Science 2011)
Challenges in Irreproducible Research (nature topic)
Not so obvious examples
Implementing a pipeline: A collection of functions that are used to process data in a specific way. e.g., CDC’s epinow2-pipeline (link).
Branding: You can create an extension for
Rmarkdown,quarto, orggplot2(to name a few) that contains your company’s colors and logos. e.g., University of Southern California’s IMAGE grant (link) (see also this for quarto formats.)Shiny apps: So it is easier to share them with other users, e.g., the
epiworldRShinyimplements a shiny-version of theepiworldRR package.Sharing Data: There are multiple R packages that only contain data, for instance, the
gapminderpackage (link).
What’s an R package, anyway?
According to Hadley Wickham’s “R packages”
Packages are the fundamental units of reproducible R code. They include reusable R functions, the documentation that describes how to use them, and sample data.
What’s an R package, anyway? (cont.)
Folders
R Where the R scripts live, e.g.,
addnums.r,boring-pkg.r.tests Where the tests live, e.g.,
testthat/test-addnums.r(using testthat or tinytest).vignettes Where vignettes live, e.g.,
vignettes/mode_details_on_addnums.rmd.data Where the data lives, e.g.,
fakedata.rda,aneattable.csv.man Where the manuals live, e.g.,
addnums.Rd,boringpkg.Rd.
And files
DESCRIPTION The metadata of the package: name, description, version, author(s), dependencies, etc.
NAMESPACE Declares the name of the objects (functions mainly) that will be part of the package (and will be visible to the user)
Dev cycle
Writing R packages is an iterative process
Set up the structure: Create folders and files
R/,data/,src/,tests/,man/,vignettes/,DESCRIPTION,NAMESPACE(?)Code! For
finFdoWrite
fDocument
f: what it does, what the inputs are, what it returns, and examples.Add some tests: is it doing what it is supposed to do?
R CMD Check: Will CRAN and the rest of the functions ‘like’ it?Commit your changes!: Update
ChangeLog+news.md, and commit (so GitHub Actions runs)!next
f
Submit your package to CRAN/Bioconductor (read more)
Dev cycle (overview)
Handson
Step 1: Set up the structure
You have several methods: package.skeleton(), Rstudio’s “New Project”, devtools::new(), etc. You can also use usethis::create_package().
Try it out!
Step 1: Set up the structure (cont. 1)
And, using the usethis package, we can add some extras. Locally:
# Creating a README for the project
usethis::use_readme_rmd()
# Infrastructure for testing
usethis::use_testthat()
# A LICENSE file (required by CRAN)
# The line "license: MIT + file" in the DESCRIPTION file
usethis::use_mit_license(copyright_holder = "George G. Vega Yon")
usethis::use_news_md()If you are planning to use GitHub, you can set up GitHub Actions. This is GitHub’s built-in automation service: it runs scripts on GitHub’s own machines whenever something happens in your repo, such as a push. This setup is often called continuous integration (CI). For this to work, your package first needs to be a Git repository that is connected to GitHub.
# Turn the package folder into a Git repository
usethis::use_git()
# Create a matching repo on GitHub and push to it
# (needs GitHub login, see the one-time setup below)
usethis::use_github()
# Some basic CI infrastructure
usethis::use_github_action("check-standard")use_git() and use_github()
- Tell Git who you are (use the email of your GitHub account):
usethis::use_git_config(user.name = "Jane Doe", user.email = "jane@example.com") - Log in to GitHub with the GitHub CLI, in a terminal:
gh auth login --scopes workflow, thengh auth setup-git. Theworkflowscope is needed to push the GitHub Actions file. No GitHub CLI? Create a token withusethis::create_github_token()and store it withgitcreds::gitcreds_set(). - Check:
usethis::git_sitrep()should show your name, email, and GitHub username.
git
From a terminal inside the package folder, this does the same as use_git():
git init
git add .
git commit -m "Initial commit"
For use_github(), first create an empty repo on github.com with the same name as your package (don’t add a README or license, since you already have them). Then connect it and push:
git branch -M main
git remote add origin https://github.com/your-username/boringpkg.git
git push -u origin main
If you have the GitHub CLI installed, gh repo create boringpkg --public --source=. --push creates the repo and pushes in one step.
Try it out! Other things we are not setting up: code coverage, which measures how much of your code your tests actually run (check out the usethis::use_coverage() function).
Step 1: Set up the structure (cont. 2)
What did happen?
use_readme_rmd(): Creates aREADME.Rmdfile in the project’s main folder. Think about it as the home page of your project. You edit the.Rmdand knit it intoREADME.md, which is what GitHub shows on the repo page. Since it can run R code, you can include working examples.use_testthat(): Sets up the testing infrastructure. It creates thetests/testthat/folder (your test files go there) andtests/testthat.R(the scriptR CMD checkuses to run them), and addstestthattoSuggestsinDESCRIPTION.use_mit_license(copyright_holder = "George G. Vega Yon"): Creates theLICENSEfile and puts it under ‘George G. Vega Yon’. It also setsLicense: MIT + file LICENSEinDESCRIPTION. Without a license, others can’t legally reuse your code.use_news_md(): Creates theNEWS.mdfile, which is used for tracking changes and communicating them to the users (e.g. netdiffuseR). Add a short entry every time you release a new version.use_git()anduse_github():use_git()initializes a Git repository in the package folder and offers to make a first commit.use_github()creates a repo with the same name on your GitHub account, connects it to your local one, and pushes your files. It needs to be able to log in to GitHub for you, through the GitHub CLI or a personal access token (see the one-time setup above, and Happy Git for details).use_github_action("check-standard"): Adds the workflow file.github/workflows/R-CMD-check.yaml. Every time you push to GitHub (or open a pull request), GitHub runsR CMD checkon macOS, Windows, and Ubuntu with several versions of R. You can see the results in the Actions tab of your repo. This is how you find out your package breaks on another operating system before CRAN tells you. Remember to commit and push.github/workflows/R-CMD-check.yaml: it only exists on your computer until you push it, and GitHub can only run what is in your repo.
use_github_action("check-standard") do?
On your computer, it:
- Creates
.github/workflows/R-CMD-check.yaml, a copy of the “check-standard” workflow maintained by the r-lib team (the people behinddevtoolsandusethis). - Adds
.githubto.Rbuildignore, so the folder isn’t part of the built package. - Adds a status badge to your README that shows whether the latest check passed. This step needs the GitHub repo, so run
use_github()first.
It does not commit or push anything.
On GitHub, once the file is pushed, the workflow runs on every push to main and on every pull request. It runs five checks, each on a fresh virtual machine:
| Operating system | R version |
|---|---|
| macOS | release |
| Windows | release |
| Ubuntu | devel |
| Ubuntu | release |
| Ubuntu | oldrel-1 (the previous version of R) |
Each check installs R and your package’s dependencies, then runs R CMD check. A check fails if there are any errors or warnings. Notes are allowed.
You can change which systems and R versions are checked by editing the matrix section of the YAML file.
Now that we have the structure, we can start coding!
Step 2.1 and 2.2: Write f and Document it
Using
roxygen2is very straight forward. For our fist pice of code, we create theR/addnums.rfile (right).Type
devtools::document(), or press Ctrl + Shift + D (RStudio will: create the manual and the NAMESPACE). Make sure you activate this option in RStudio (not the default).Notice that the output is defined using S3-type objects (read more)
#' The title of -addnums-
#'
#' Here is a brief description
#'
#' @param a Numeric scalar. A brief description.
#' @param b Numeric scalar. A brief description.
#'
#' @details Computes the sum of \code{x} and \code{y}.
#' @return A list of class \code{boringpkg_addnums}:
#' \item{a}{Numeric scalar.}
#' \item{b}{Numeric scalar.}
#' \item{ab}{Numeric scalar. the sum of \code{a} and \code{b}}
#' @examples
#' foo(1, 2)
#'
#' @export
addnums <- function(a, b) {
ans <- a + b
structure(list(a = a, b = b, ab = ans)
, class = "boringpkg_addnums")
}devtools::document() do?
It runs roxygen2 on the #' comments in your R/ files and writes two things from them:
man/*.Rdfiles: the help pages behind?addnums. Tags like@param,@return, and@examplesbecome sections of the page. Don’t edit these by hand, since the nextdocument()overwrites them.The
NAMESPACEfile:@exportbecomesexport(addnums), so users can call the function.@importFrom graphics axisbecomesimportFrom(graphics, axis).
Run it again every time you change a roxygen comment, otherwise the help pages and NAMESPACE fall out of date. Note that it does not touch Imports in DESCRIPTION. You add those yourself, e.g., with usethis::use_package("graphics").
Detour: Why use S3 in a package?
addnums() returns a list with a class attribute. This is S3, the object system used by most of base R and CRAN, and it has several advantages:
Users already know the functions: If your output has a class, users can call
print(),summary(), orplot()on it, just like they do with the output oflm().Results stay together: A classed list keeps the inputs and the result in one object.
addnums()returnsa,b, andabtogether.Others can extend it: Another package can add a method for your class without changing your code.
It’s lightweight: Turning a list into an S3 object takes one line,
class(x) <- "boringpkg_addnums". In S4 or S7, you first have to declare the class and the type of each field before you can create an object.
R also has other object systems. S4 is more formal and is used throughout Bioconductor. R6 gives objects that can be modified in place. S7 is the newest one, built by the R Consortium as a successor to S3 and S4. S7 objects are also S3 objects, so what you learn here carries over.
Read more in the S3 chapter of Hadley Wickham’s Advanced R.
For a long time, R package authors had two main choices. S3 is simple but informal: there is no way to say which fields an object should have, so it’s easy to create broken objects. S4 fixes that, but it’s verbose and harder to learn. Having two systems also split the community, with most of CRAN using S3 and Bioconductor using S4.
S7 was developed by the R Consortium’s object-oriented programming working group, which includes members of R Core, Bioconductor, and the tidyverse team. The goal was a single system that keeps the simplicity of S3, adds the formal class definitions and validation of S4, and works with existing S3 and S4 code. The long-term plan is to include it in base R.
S7 classes are defined up front, with typed properties. Properties are accessed with @.
library(S7)
addnums <- new_class("addnums", properties = list(
a = class_numeric,
b = class_numeric,
ab = new_property(class_numeric, getter = function(self) self@a + self@b)
))
x <- addnums(a = 1, b = 2)
x@ab
#> [1] 3
# Methods are registered with method()
method(print, addnums) <- function(x, ...) cat(x@a, "+", x@b, "=", x@ab, "\n")
x
#> 1 + 2 = 3Passing a = "one" gives an error, since a must be numeric. With S3, nothing stops you from creating a broken object.
So should you use S7? For most packages, S3 is still the default. It’s part of base R, most packages you’ll read use it, and tools like roxygen2 are built around it. S7 is still a separate package (not yet 1.0), so using it adds a dependency. Consider S7 when your objects have many fields that need checking, or when a method should depend on more than one argument. It is already used in production: ggplot2 4.0 moved its internals to S7.
See the S7 documentation for more.
Detour: S3 classes
Here we are leveraging S3 classes. In R, the S3 is a simple way to do object oriented programming. The way it works:
Objects should have a class attribute (e.g.,
class(x) <- "myclass").You can then define “methods” for that class, e.g.,
print.myclassandplot.myclass.These are valid as long as there is a generic function (e.g.,
printandplot) that can handle the class.
You can inspect the methods using the methods() function, e.g.,
methods(generic.function = "print") [1] print.acf*
[2] print.activeConcordance*
[3] print.AES*
[4] print.anova*
[5] print.aov*
[6] print.aovlist*
[7] print.ar*
[8] print.Arima*
[9] print.arima0*
[10] print.AsIs
[11] print.aspell*
[12] print.aspell_inspect_context*
[13] print.bibentry*
[14] print.Bibtex*
[15] print.browseVignettes*
[16] print.by
[17] print.changedFiles*
[18] print.check_bogus_return*
[19] print.check_code_usage_in_package*
[20] print.check_compiled_code*
[21] print.check_demo_index*
[22] print.check_depdef*
[23] print.check_details*
[24] print.check_details_changes*
[25] print.check_doi_db*
[26] print.check_dotInternal*
[27] print.check_make_vars*
[28] print.check_nonAPI_calls*
[29] print.check_package_code_assign_to_globalenv*
[30] print.check_package_code_attach*
[31] print.check_package_code_data_into_globalenv*
[32] print.check_package_code_startup_functions*
[33] print.check_package_code_syntax*
[34] print.check_package_code_unload_functions*
[35] print.check_package_compact_datasets*
[36] print.check_package_CRAN_incoming*
[37] print.check_package_datalist*
[38] print.check_package_datasets*
[39] print.check_package_depends*
[40] print.check_package_description*
[41] print.check_package_description_encoding*
[42] print.check_package_license*
[43] print.check_packages_in_dir*
[44] print.check_packages_used*
[45] print.check_po_files*
[46] print.check_pragmas*
[47] print.check_Rd_line_widths*
[48] print.check_Rd_metadata*
[49] print.check_Rd_xrefs*
[50] print.check_RegSym_calls*
[51] print.check_S3_methods_needing_delayed_registration*
[52] print.check_so_symbols*
[53] print.check_T_and_F*
[54] print.check_url_db*
[55] print.check_vignette_index*
[56] print.checkDocFiles*
[57] print.checkDocStyle*
[58] print.checkFF*
[59] print.checkRd*
[60] print.checkRdContents*
[61] print.checkReplaceFuns*
[62] print.checkS3methods*
[63] print.checkTnF*
[64] print.checkVignettes*
[65] print.citation*
[66] print.cli_ansi_html_style*
[67] print.cli_ansi_string*
[68] print.cli_ansi_style*
[69] print.cli_boxx*
[70] print.cli_diff_chr*
[71] print.cli_doc*
[72] print.cli_progress_demo*
[73] print.cli_rule*
[74] print.cli_sitrep*
[75] print.cli_spark*
[76] print.cli_spinner*
[77] print.cli_tree*
[78] print.codoc*
[79] print.codocClasses*
[80] print.codocData*
[81] print.colorConverter*
[82] print.compactPDF*
[83] print.condition
[84] print.connection
[85] print.CRAN_package_reverse_dependencies_and_views*
[86] print.data.frame
[87] print.Date
[88] print.default
[89] print.dendrogram*
[90] print.density*
[91] print.difftime
[92] print.dist*
[93] print.Dlist
[94] print.DLLInfo
[95] print.DLLInfoList
[96] print.DLLRegisteredRoutines
[97] print.dummy_coef*
[98] print.dummy_coef_list*
[99] print.ecdf*
[100] print.eigen
[101] print.evaluate_evaluation*
[102] print.factanal*
[103] print.factor
[104] print.family*
[105] print.fileSnapshot*
[106] print.findLineNumResult*
[107] print.formula*
[108] print.ftable*
[109] print.function
[110] print.getAnywhere*
[111] print.glm*
[112] print.hashtab*
[113] print.hclust*
[114] print.help_files_with_topic*
[115] print.hexmode
[116] print.HoltWinters*
[117] print.hsearch*
[118] print.hsearch_db*
[119] print.htest*
[120] print.html*
[121] print.html_dependency*
[122] print.htmltools.selector*
[123] print.htmltools.selector.list*
[124] print.htmlwidget*
[125] print.infl*
[126] print.integrate*
[127] print.isoreg*
[128] print.json*
[129] print.key_missing*
[130] print.kmeans*
[131] print.knitr_kable*
[132] print.Latex*
[133] print.LaTeX*
[134] print.libraryIQR
[135] print.listof
[136] print.lm*
[137] print.loadings*
[138] print.loess*
[139] print.logLik*
[140] print.ls_str*
[141] print.medpolish*
[142] print.MethodsFunction*
[143] print.mtable*
[144] print.NativeRoutineList
[145] print.news_db*
[146] print.nls*
[147] print.noquote
[148] print.numeric_version
[149] print.object_size*
[150] print.octmode
[151] print.otel_counter*
[152] print.otel_gauge*
[153] print.otel_histogram*
[154] print.otel_logger*
[155] print.otel_logger_provider*
[156] print.otel_meter*
[157] print.otel_meter_provider*
[158] print.otel_span*
[159] print.otel_span_context*
[160] print.otel_tracer*
[161] print.otel_tracer_provider*
[162] print.otel_up_down_counter*
[163] print.packageDescription*
[164] print.packageInfo
[165] print.packageIQR*
[166] print.packageStatus*
[167] print.paged_df*
[168] print.pairwise.htest*
[169] print.person*
[170] print.POSIXct
[171] print.POSIXlt
[172] print.power.htest*
[173] print.ppr*
[174] print.prcomp*
[175] print.princomp*
[176] print.proc_time
[177] print.quosure*
[178] print.quosures*
[179] print.raster*
[180] print.Rconcordance*
[181] print.Rd*
[182] print.recordedplot*
[183] print.restart
[184] print.RGBcolorConverter*
[185] print.RGlyphFont*
[186] print.rlang_box_done*
[187] print.rlang_box_splice*
[188] print.rlang_data_pronoun*
[189] print.rlang_dict*
[190] print.rlang_dyn_array*
[191] print.rlang_envs*
[192] print.rlang_error*
[193] print.rlang_fake_data_pronoun*
[194] print.rlang_lambda_function*
[195] print.rlang_message*
[196] print.rlang_trace*
[197] print.rlang_warning*
[198] print.rlang_zap*
[199] print.rlang:::list_of_conditions*
[200] print.rle
[201] print.rlib_bytes*
[202] print.rlib_error_3_0*
[203] print.rlib_trace_3_0*
[204] print.roman*
[205] print.scalar*
[206] print.sessionInfo*
[207] print.shiny.tag*
[208] print.shiny.tag.env*
[209] print.shiny.tag.list*
[210] print.shiny.tag.query*
[211] print.simple.list
[212] print.smooth.spline*
[213] print.socket*
[214] print.srcfile
[215] print.srcref
[216] print.stepfun*
[217] print.stl*
[218] print.StructTS*
[219] print.subdir_tests*
[220] print.summarize_CRAN_check_status*
[221] print.summary.aov*
[222] print.summary.aovlist*
[223] print.summary.ecdf*
[224] print.summary.glm*
[225] print.summary.lm*
[226] print.summary.loess*
[227] print.summary.manova*
[228] print.summary.nls*
[229] print.summary.packageStatus*
[230] print.summary.ppr*
[231] print.summary.prcomp*
[232] print.summary.princomp*
[233] print.summary.table
[234] print.summary.warnings
[235] print.summaryDefault
[236] print.suppress_viewer*
[237] print.table
[238] print.tables_aov*
[239] print.terms*
[240] print.ts*
[241] print.tskernel*
[242] print.TukeyHSD*
[243] print.tukeyline*
[244] print.tukeysmooth*
[245] print.undoc*
[246] print.vignette*
[247] print.warnings
[248] print.xfun_md_viewable*
[249] print.xfun_raw_string*
[250] print.xfun_record_results*
[251] print.xfun_rename_seq*
[252] print.xfun_strict_list*
[253] print.xgettext*
[254] print.xngettext*
[255] print.xtabs*
see '?methods' for accessing help and source code
methods(class = "glm") [1] add1 anova coerce confint cooks.distance
[6] deviance drop1 effects extractAIC family
[11] formula influence initialize logLik model.frame
[16] nobs predict print profile residuals
[21] rstandard rstudent show sigma slotsFromS3
[26] summary vcov weights
see '?methods' for accessing help and source code
Detour: S3 classes (cont.)
You can also define your own methods, e.g.,:
my_generic <- function(x) UseMethod("my_generic")
my_generic.default <- function(x) "I don't know how to handle this"
my_generic.numeric <- function(x) "I know how to handle this"
my_generic("a")[1] "I don't know how to handle this"
my_generic(1)[1] "I know how to handle this"
Exporting methods: Put
@exportabove a method likeplot.boringpkg_addnums(). When you rundevtools::document(), roxygen sees that it is a method for theplotgeneric and writesS3method(plot, boringpkg_addnums)toNAMESPACE. Without this, callingplot()on your object from outside the package won’t use your method, andR CMD checkwill complain.Constructors: The usual pattern is one function that checks the inputs and then sets the class, so every object of your class has the same structure.
addnums()is a simple version of this, usingstructure(..., class = "boringpkg_addnums").Naming: Prefix your class names with the package name (
boringpkg_addnums) so they don’t clash with classes from other packages.
Step 2.1 and 2.2: Write f and Document it (cont. 1)
Here we are defining a method for plot.boringpkg_addnums. Notice that the plot function already has a generic method, which is why we only need to define the method for boringpkg_addnums.
#' @rdname addnums
#' @export
#' @param x An object of class \code{boringpkg_addnums}.
#' @param y Ignored.
#' @param ... Further arguments passed to
#' \code{\link[graphics:plot.window]{plot.window}}.
plot.boringpkg_addnums <- function(x, y = NULL, ...) {
graphics::plot.new()
graphics::plot.window(xlim = range(unlist(c(0,x))), ylim = c(-.5,1))
graphics::axis(1)
with(x, graphics::segments(0, 1, ab, col = "blue", lwd=3))
with(x, graphics::segments(0, 0, a, col = "green", lwd=3))
with(x, graphics::segments(a, .5, a + b, col = "red", lwd=3))
graphics::legend("bottom", col = c("blue", "green", "red"),
legend = c("a+b", "a", "b"), bty = "n",
ncol = 3, lty = 1, lwd=3)
}Here, we are adding a function that is documented in
addnums. The plot method (above).You’ll need to update the
man/*Rdevery time that you add new roxygen content. Press Ctrl + Shift + D, and RStudio will do it for you (or enterdevtools::document()which callsroxygen2::roxygenize()).Notice that functions from foreign packages are called using the
::operator (read more here and here). Not a requirement, but makes the code easier to maintain (and less error-prone… because of R’s scoping rules).
Step 2.1 and 2.2: Write f and Document it (cont. 2)
Our plot method uses foreign functions (i.e., function from the graphics package), so we need to declare that dependency. We also add a help page for the package as a whole.
R/boringpkg-package.R
#' boringpkg
#'
#' A (not so) boring collection of functions
#'
#' @description We add stuff up... You can access the project
#' website at \url{https://github.com/USCbiostats/software-dev/tree/master/rpkgs/boringpkg}
#'
#' @author George G. Vega Yon
#' @keywords internal
"_PACKAGE"
## usethis namespace: start
#' @importFrom graphics axis legend plot.new plot.window segments
## usethis namespace: end
NULLDESCRIPTION
Package: boringpkg
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Author: Who wrote it
Maintainer: The package maintainer <yourself@somewhere.net>
Description: More about what it does (maybe more than one line)
Use four spaces when indenting paragraphs within the Description.
License: What license is it under?
Encoding: UTF-8
LazyData: true
Suggests:
testthat,
covr
RoxygenNote: 5.0.1
Imports: graphicsusethis::use_package_doc()creates this file."_PACKAGE"tells roxygen to build the?boringpkghelp page, an overview of the whole package. By default, it fills in the title, description, and authors fromDESCRIPTION. You can write your own text above"_PACKAGE", as we do here, to give users a longer overview or a link to the project website.@keywords internalkeeps this page out of the list of functions in the help index.The
usethis namespacesection holds imports for the whole package.usethis::use_import_from("graphics", "axis")adds tags there for you. TheNULLat the end is needed because a roxygen block has to sit above an object.usethis::use_package("graphics")addsgraphicstoImportsinDESCRIPTION. Every package your code uses must be listed there, orR CMD checkwill complain. TheSuggestsandRoxygenNotefields were added automagically bydevtools.
@importFrom or pkg::fun()?
There are two ways to use a function from another package:
graphics::axis(): you call it with the package name in front. No import is needed, only theImportsentry inDESCRIPTION. It’s always clear where the function comes from.@importFrom graphics axis: you can then writeaxis()directly. This is handy for functions you use a lot, or ones that are awkward to write with::, like the pipe%>%frommagrittr.
Our plot method uses graphics:: everywhere, so strictly the @importFrom line isn’t needed here. We show it so you know what it looks like. In your own package, pick one style and stick with it.
You may also see older packages document themselves with @docType package and @name boringpkg above a NULL. That still works, but "_PACKAGE" is the current recommended way.
Step 2.3: Add some tests
Test are run every time that you run R CMD check
In the
tests/testthat/dir, add/edit a source file with tests, e.g.test-addnums.rtest_that("addnums(a, b) = a+b", { # Preparing the test a <- 1 b <- -2 # Calling the function ans0 <- a+b ans1 <- addnums(a, b) # Are these equal? expect_equal(ans0, ans1$ab) }) test_that("Plot returns -boringpkg_foo-", { expect_s3_class( plot(addnums(1,2)), "boringpkg_foo" ) # This will generate an error as the function plot.boringpkg_addnum # does not return an object of that class. })You can run the tests using Ctrl + Shift + t
Furthermore, tests are used to evaluate code coverage.
Step 2.4: R CMD check
R CMD check is R’s built-in tool for testing a whole package. It builds and installs the package, then runs a long list of checks: whether the DESCRIPTION is valid, whether every exported function is documented, whether the examples run, whether the tests pass, and whether the code uses packages it doesn’t declare. It reports back errors, warnings, and notes. CRAN runs the same checks on every submission, so a clean check locally is the first thing to aim for. From R, devtools::check() runs it for you.
R CMD check mean?
The name. R CMD runs R’s command-line tools from a terminal, not from the R console. check is one of them. Others are R CMD build (bundles the package into a .tar.gz) and R CMD INSTALL. You should check the built .tar.gz, not the source folder, because that file is what users and CRAN receive.
The results. Each problem is reported at one of three levels:
| Level | Meaning | For CRAN |
|---|---|---|
| ERROR | Something is broken, e.g., the package doesn’t install or a test fails | Must fix |
| WARNING | Likely a problem, e.g., the help file doesn’t match the function’s arguments | Must fix |
| NOTE | Minor, or something to look at | Keep to a minimum, and explain any that remain |
The full logs, including example and test output, are saved in a boringpkg.Rcheck/ folder. Look there when something fails.
devtools::check() runs document(), builds the .tar.gz, and then runs R CMD check --as-cran on it. The --as-cran option turns on CRAN’s stricter checks.
Running R CMD check is easy with RStudio
If you don’t have C/C++ code Just press Ctrl + Shift + E
If you have C/C++ code, use
R CMD Checkwith valgrind (check for segfaults)$ R CMD build boringpkg/ $ R CMD check --as-cran --use-valgrind boringpkg*.tar.gzYou can ask RStudio to use valgrind too.
For an extensive list of the checks, see the section 1.3.1 Checking packages in the “Writing R extensions” manual.
What does the output of R CMD check looks like?
==> devtools::check()
Updating boringpkg documentation
Loading boringpkg
Setting env vars ---------------------------------------------------------------
CFLAGS : -Wall -pedantic
CXXFLAGS: -Wall -pedantic
Building boringpkg --------------------------------------------------------------
'/usr/lib/R/bin/R' --no-site-file --no-environ --no-save --no-restore --quiet \
CMD build \
'/home/vegayon/Dropbox/usc/core_project/CodingStandards/rpkgs/boringpkg' \
--no-resave-data --no-manual
* checking for file ‘/home/vegayon/Dropbox/usc/core_project/CodingStandards/rpkgs/boringpkg/DESCRIPTION’ ... OK
* preparing ‘boringpkg’:
* checking DESCRIPTION meta-information ... OK
* checking for LF line-endings in source and make files
* checking for empty or unneeded directories
* building ‘boringpkg_0.1.999.tar.gz’
Setting env vars ---------------------------------------------------------------
_R_CHECK_CRAN_INCOMING_USE_ASPELL_: TRUE
_R_CHECK_CRAN_INCOMING_ : FALSE
_R_CHECK_FORCE_SUGGESTS_ : FALSE
Checking boringpkg --------------------------------------------------------------
'/usr/lib/R/bin/R' --no-site-file --no-environ --no-save --no-restore --quiet \
CMD check '/tmp/RtmpBYGSto/boringpkg_0.1.999.tar.gz' --as-cran --timings \
--no-manual
* using log directory ‘/home/vegayon/Dropbox/usc/core_project/CodingStandards/rpkgs/boringpkg.Rcheck’
* using R version 3.3.2 (2016-10-31)
* using platform: x86_64-pc-linux-gnu (64-bit)
* using session charset: UTF-8
* using options ‘--no-manual --as-cran’
* checking for file ‘boringpkg/DESCRIPTION’ ... OK
* checking extension type ... Package
* this is package ‘boringpkg’ version ‘0.1.999’
* package encoding: UTF-8
* checking package namespace information ... OK
* checking package dependencies ... OK
* checking if this is a source package ... OK
* checking if there is a namespace ... OK
* checking for executable files ... OK
* checking for hidden files and directories ... OK
* checking for portable file names ... OK
* checking for sufficient/correct file permissions ... OK
* checking whether package ‘boringpkg’ can be installed ... OK
* checking installed package size ... OK
* checking package directory ... OK
* checking DESCRIPTION meta-information ... OK
* checking top-level files ... OK
* checking for left-over files ... OK
* checking index information ... OK
* checking package subdirectories ... OK
* checking R files for non-ASCII characters ... OK
* checking R files for syntax errors ... OK
* checking whether the package can be loaded ... OK
* checking whether the package can be loaded with stated dependencies ... OK
* checking whether the package can be unloaded cleanly ... OK
* checking whether the namespace can be loaded with stated dependencies ... OK
* checking whether the namespace can be unloaded cleanly ... OK
* checking loading without being on the library search path ... OK
* checking dependencies in R code ... OK
* checking S3 generic/method consistency ... OK
* checking replacement functions ... OK
* checking foreign function calls ... OK
* checking R code for possible problems ... OK
* checking Rd files ... OK
* checking Rd metadata ... OK
* checking Rd line widths ... OK
* checking Rd cross-references ... OK
* checking for missing documentation entries ... OK
* checking for code/documentation mismatches ... OK
* checking Rd \usage sections ... OK
* checking Rd contents ... OK
* checking for unstated dependencies in examples ... OK
* checking examples ... OK
* checking for unstated dependencies in ‘tests’ ... OK
* checking tests ...
Running ‘testthat.R’ OK
* DONE
Status: OK
R CMD check results
0 errors | 0 warnings | 0 notes
R CMD check succeeded
Step 2.4: R CMD check (cont. 1)
R packages can be shared by “building” them. For example, the following command:
R CMD build ~/Documents/boringpkg
Will generate package the R package into a file named boringpkg_0.1.0.tar.gz that can later be distributed. Users can install this package either through command line:
R CMD INSTALL boringpkg_0.1.0.tar.gz
Or through the console in R
install.packages("boringpkg_0.1.0.tar.gz", repos = NULL)Step 2.5: Commit your changes
Once you have run R CMD checks and no errors or unexpected issues are detected, you should commit your changes and push them to Github.
Edit the
NEWS.mdfile and theChangeLog(if you have one).NEWS.mdis a changelog written for your users. It lists what changed in each version: new functions, bug fixes, and changes that might break their code. Each version gets a heading, and each change gets a short bullet:# boringpkg (development version) * New `plot()` method for `addnums()` output. # boringpkg 0.1.0 * Initial release.CRAN shows this file on your package’s page, and users can read it from R with
news(package = "boringpkg"). It’s easiest to add a bullet every time you make a change, so it’s ready when you release.Add the new files to the tree, commit your changes, and push them to Github
$ git add R/newfile.r man/newfile.Rd $ git commit -a -m "Adding new function" $ git push
Once uploaded, check the Actions tab of your GitHub repo to see if R CMD check passed on all operating systems.
Older packages and tutorials mention Travis CI and AppVeyor. These were CI services that did the same job before GitHub Actions existed: Travis for Linux and macOS, AppVeyor for Windows. Around 2020 to 2021, Travis stopped offering its free plan for open-source projects. Most R packages then moved to GitHub Actions, which is free for public repos, runs on all three operating systems, and is set up with a single usethis call.
Step 3: Submit your package to CRAN/Bioconductor
These are the two main places where R users get packages:
CRAN (the Comprehensive R Archive Network) is R’s official package repository. When someone runs
install.packages("boringpkg"), this is where the package comes from. It hosts packages from every field. Submissions are reviewed by volunteers, and your package has to passR CMD checkon several operating systems. After acceptance, CRAN keeps checking it as R and other packages change, and may remove it if it starts failing.Bioconductor is a repository for packages that analyze biological data, mostly genomics. Users install from it with
BiocManager::install(). Each submission gets a code review from a Bioconductor team member, it must include a vignette, and it should reuse Bioconductor’s existing data structures where possible. New versions come out twice a year.
If your package isn’t about biological data, CRAN is the usual choice.
To submit to CRAN:
Run
usethis::use_release_issue(). It opens a GitHub issue with a checklist of everything to do before a release (see “Before you submit to CRAN” below).Work through the checklist.
Run
devtools::submit_cran(). It builds the package and uploads it to CRAN. CRAN then emails you a link to confirm the submission.
CRAN started in 1997 and is run by a small team of volunteers under the R Foundation for Statistical Computing, a non-profit in Vienna that holds the copyright to R. Its main server is hosted at the Vienna University of Economics and Business (WU Wien).
CRAN distributes R itself (the installers for Windows and macOS, and the source code) and over 20,000 packages. It checks every package regularly on several operating systems and R versions, and archives packages that start failing.
CRAN is copied to many servers (“mirrors”) around the world, run by universities and companies, so downloads are fast everywhere. The default in RStudio, cloud.r-project.org, is a mirror run by Posit that sends you to a nearby server.
Because a handful of volunteers handle thousands of packages, CRAN relies on automated checks and expects maintainers to follow its rules closely. This is why reviews can feel strict. The rules are in the CRAN Repository Policy.
devtools::check()locally: 0 errors, 0 warnings. Explain any notes incran-comments.md(create it withusethis::use_cran_comments()).devtools::check_win_devel(): checks your package on CRAN’s Windows machine with the development version of R. Results arrive by email.- The GitHub Actions check passes on all operating systems.
- Update the version number (
usethis::use_version()) andNEWS.md.
These are the main items on the use_release_issue() checklist. After you submit, CRAN runs its own automatic checks, and then a volunteer reviews the package.
devtools::release()?
For many years, devtools::release() was the standard way to submit. It asked you a series of yes/no questions (Did you run R CMD check? Did you update NEWS.md?) and then submitted the package. Hadley Wickham, the author of devtools, was so confident in it that its help page came with a warranty:
If a devtools bug causes one of the CRAN maintainers to treat you impolitely, I will personally send you a handwritten apology note. Please forward me the email and your address, and I’ll get a card in the mail.
release() is now deprecated. The devtools team no longer uses it themselves, so they can’t promise it follows current best practices. The checklist from use_release_issue() replaces the questions, and submit_cran() does the uploading. You will still see release() in older tutorials.
Dev Cycle (once again!)
The most important step
Code! For
finFdoWrite
fDocument
f: what it does, what the inputs are, what it returns, examples.Add some tests: is it doing what is supposed to do?
R CMD Check: Will CRAN, and the rest of the functions, ‘like’ it?Commit your changes!: Update
ChangeLog+news.md, and commit (so GitHub Actions runs)!next
f
Fin
devtools::session_info()─ Session info ───────────────────────────────────────────────────────────────
setting value
version R version 4.5.3 (2026-03-11)
os Ubuntu 24.04.4 LTS
system x86_64, linux-gnu
ui X11
language (EN)
collate en_US.UTF-8
ctype en_US.UTF-8
tz Etc/UTC
date 2026-11-24
pandoc 3.9 @ /usr/bin/ (via rmarkdown)
quarto 1.9.35 @ /usr/local/bin/quarto
─ Packages ───────────────────────────────────────────────────────────────────
package * version date (UTC) lib source
cachem 1.1.0 2024-05-16 [1] RSPM
cli 3.6.5 2025-04-23 [1] RSPM
devtools 2.4.6 2025-10-03 [1] RSPM
digest 0.6.39 2025-11-19 [1] RSPM
ellipsis 0.3.2 2021-04-29 [1] RSPM
evaluate 1.0.5 2025-08-27 [1] RSPM
fastmap 1.2.0 2024-05-15 [1] RSPM
fs 1.6.7 2026-03-06 [1] RSPM
glue 1.8.0 2024-09-30 [1] RSPM
htmltools 0.5.9 2025-12-04 [1] RSPM
htmlwidgets 1.6.4 2023-12-06 [1] RSPM
jsonlite 2.0.0 2025-03-27 [1] RSPM
knitr 1.51 2025-12-20 [1] RSPM
lifecycle 1.0.5 2026-01-08 [1] RSPM
magrittr 2.0.4 2025-09-12 [1] RSPM
memoise 2.0.1 2021-11-26 [1] RSPM
otel 0.2.0 2025-08-29 [1] RSPM
pkgbuild 1.4.8 2025-05-26 [1] RSPM
pkgload 1.5.0 2026-02-03 [1] RSPM
purrr 1.2.1 2026-01-09 [1] RSPM
R6 2.6.1 2025-02-15 [1] RSPM
remotes 2.5.0 2024-03-17 [1] RSPM
rlang 1.1.7 2026-01-09 [1] RSPM
rmarkdown 2.30 2025-09-28 [1] RSPM
sessioninfo 1.2.3 2025-02-05 [1] RSPM
usethis 3.2.1 2025-09-06 [1] RSPM
vctrs 0.7.1 2026-01-23 [1] RSPM
xfun 0.56 2026-01-18 [1] RSPM
yaml 2.3.12 2025-12-10 [1] RSPM
[1] /usr/local/lib/R/site-library
[2] /usr/local/lib/R/library
──────────────────────────────────────────────────────────────────────────────
More resources
“Writing R extensions” (R Core Team)
“R packages” (Hadley Wickham)
“Developing Packages with RStudio” (Josh Paulson)
“A template for R packages using Rcpp and/or RcppArmadillo” (Patrick Muchmore)
“R package primer: a minimal tutorial” (Karl Broman)
“Writing an R package from scratch” (Hilary Parker)
“Instructions for Creating Your Own R Package” (Kim et al.)