5.6 Foxtrot: build time vs. run time
Another problem:: timestamps don’t seem to work properly.
Sys.time()
#> [1] "2022-02-24 20:49:59 PST"
outfile_path("INFILE.csv")
#> [1] "2020-September-03_11-06-33_INFILE_clean.csv"
The timestamp reflects the time that the function was initially run, rather than the current time.
Recall how we form the filepath for output files:
now <- Sys.time()
timestamp <- function(time) format(time, "%Y-%B-%d_%H-%M-%S")
outfile_path <- function(infile) {
paste0(timestamp(now), "_", sub("(.*)([.]csv$)", "\\1_clean\\2", infile))
}
Source of the problem: The now <- Sys.time()
function lies outside the outfile_path
definition, so it is executed when the package is built, but never again. Code outside your functions is only built once at build time.
Moving now <- Sys.time
so that it’s no longer top level code:
# always timestamp as "now"
outfile_path <- function(infile) {
now <- timestamp(Sys.time())
paste0(now, "_", sub("(.*)([.]csv$)", "\\1_clean\\2", infile))
}
# allow user to provide a time, but default to "now"
outfile_path <- function(infile, time = Sys.time()) {
now <- timestamp(time)
paste0(now, "_", sub("(.*)([.]csv$)", "\\1_clean\\2", infile))
}
Need to have a different mindset when defining objects inside a package. The objects should be functions and these functions should (generally) only use data they create or that is passed via an argument.