5.4 Delta: an attempt at a package

  • Use usethis::create_package() to scaffold a new R package
  • Copy cleaning-helpers.R into the new package, specifically, to R/cleaning-helpers.R
  • Copy beach-lookup-table.csv into the top-level of the new source package
  • Install package

Script we’re trying to run:

library(tidyverse)
library(delta) # instead of source("cleaning-helpers.R")

infile <- "swim.csv"
dat <- read_csv(infile, col_types = cols(name = "c", where = "c", temp = "d"))

dat <- dat %>% 
  localize_beach() %>% 
  celsify_temp()

write_csv(dat, outfile_path(infile))

Results when we try to run this code:

library(tidyverse)
library(delta)

infile <- "swim.csv"
dat <- read_csv(infile, col_types = cols(name = "c", where = "c", temp = "d"))

dat <- dat %>% 
  localize_beach() %>% 
  celsify_temp()
> Error in localize_beach(.) : could not find function "localize_beach"

write_csv(dat, outfile_path(infile))
> Error in outfile_path(infile) : could not find function "outfile_path"

Despite calling library(delta), none of the functions were actually available to use.

  • Attaching a package does not put the functions in the global workspace. - In contrast to source()-ing a file of helper functions, attaching a package does not dump its functions into the global workspace. - By default, functions in a package are only for internal use - We can export these functions properly by putting @export in the roxygen comment above each function (See Section 10.4 for more information on DESCRIPTION)
#' @export
celsify_temp <- function(dat) {
  mutate(dat, temp = if_else(english == "US", f_to_c(temp), temp))
}

Now our script works (sort of)!

library(tidyverse)
library(delta)

infile <- "swim.csv"
dat <- read_csv(infile, col_types = cols(name = "c", where = "c", temp = "d"))

dat <- dat %>% 
  localize_beach() %>% 
  celsify_temp()
#> Error: 'beach-lookup-table.csv' does not exist in current working directory ('/Users/jenny/tmp').

write_csv(dat, outfile_path(infile))

Problem: You can’t dump CSV files into the source of an R package and expect it to work. Despite this, you can still install and attach this package.

  • This means that broken packages can still be used. To prevent this, you should run R CMD check or check() often during development.
    • Doing so will alert you to the problem:
* installing *source* package ‘delta’ ...
** using staged installation
** R
** byte-compile and prepare package for lazy loading
Error in library(tidyverse) : there is no package called ‘tidyverse’
Error: unable to load R code in package ‘delta’
Execution halted
ERROR: lazy loading failed for package ‘delta’
* removing ‘/Users/brendan/RScripts/delta.Rcheck/delta’

What is the reason behind this error?

  • Package was declared incorrectly
    • While you can load a package using library(tidyverse) in a script, dependencies on other packages must be declared in the DESCRIPTION