5.5 Echo: a working package

Now we’ll make a package that actually works:

lookup_table <- dplyr::tribble(
      ~where, ~english,
     "beach",     "US",
     "coast",     "US",
  "seashore",     "UK",
   "seaside",     "UK"
)

#' @export
localize_beach <- function(dat) {
  dplyr::left_join(dat, lookup_table)
}

f_to_c <- function(x) (x - 32) * 5/9

#' @export
celsify_temp <- function(dat) {
  dplyr::mutate(dat, temp = dplyr::if_else(english == "US", f_to_c(temp), temp))
}

now <- Sys.time()
timestamp <- function(time) format(time, "%Y-%B-%d_%H-%M-%S")

#' @export
outfile_path <- function(infile) {
  paste0(timestamp(now), "_", sub("(.*)([.]csv$)", "\\1_clean\\2", infile))
}

Note: To fix our initial problem with loading a CSV file, we’ve created a dataframe lookup_table. However, Chapter 8 Data provides more guidance and recommendations on how to load datasets properly.

Other Note: When calling functions from other packages, we should specify the package that we’re using (e.g., dplyr::mutate()). Moreover, we should identify the specific package being used, rather than the meta-package (e.g., do not use tidyverse::mutate())

  • All of the user-facing functions have an @export tag in their roxygen comment, which means that devtools::document() adds them correctly to the NAMESPACE file.

This package can be installed, but we receive 1 note and 1 warning:

* checking R code for possible problems ... NOTE
celsify_temp: no visible binding for global variable ‘english’
celsify_temp: no visible binding for global variable ‘temp’
Undefined global functions or variables:
  english temp

* checking for missing documentation entries ... WARNING
Undocumented code objects:
  ‘celsify_temp’ ‘localize_beach’ ‘outfile_path’
All user-level objects in a package should have documentation entries.
See chapter ‘Writing R documentation files’ in the ‘Writing R
Extensions’ manual.

Translation of first warnings: no visible binding for global variable ‘english’ and no visible binding for global variable ‘temp’

  • Using bare variable names like english and temp looks suspicious because you’re using unquoted variable names from dplyr inside a package.
    • Defining these variables globally eliminates the note:
option 1 (then you should also put utils in Imports)
utils::globalVariables(c("english", "temp"))

option 2
english <- temp <- NULL

The other note we received from R:

"Undocumented code objects: ‘celsify_temp’ ‘localize_beach’ ‘outfile_path’ All user-level objects in a package should have documentation entries."

This is caused by not documenting exported functions. Using roxygen comments to document it should solve the problem. (Function documentation is discussed in Chapter 16).