4

I would like to add a fallback dependency to my package. Problem is I want to do it CRAN compliant and can't figure out how to do it properly.

More specificly, I want to use data.table's fread / fwrite. Other than that I do not want to have a full data.table dependency. If data.table is not installed, my package should just fall back to using standard read.csv and write.csv.

I've seen this similar thread: Proper way to handle optional package dependencies

and also used a technique similar to what @Hadley suggested in the comments:

req <- require(data.table)
if(req){ 
   data.table::fwrite(...)
 } else {
    write.csv(...)     

  }

This does work, but when running CHECK I get a NOTE:

'library' or 'require' call to ‘data.table’ in package code. Please use :: or requireNamespace() instead.

Which means I won't get it past CRAN's supervisors...

What's the correct way to handle this?

Matt Bannert
  • 27,631
  • 38
  • 141
  • 207

1 Answers1

13

Just as the text says:

  • replace your (outdated) call to require() with one to requireNamespace()
  • Then, in the TRUE cases, call the package.
  • I often use :: to refer to the suggested package.

So mocking this up (and note, untested) I'd do

myreader <- function(file) {
    if (requireNamespace("data.table", quietly=TRUE)) {
       dat <- data.table::fread(file)
    } else {
       dat <- read.csv(file)
    }
    ## postprocess dat as needed
    dat
}

Searches at GitHub are useful with user:cran l=R yourTerm so try this one. I use the very idiom in a number of packages.

Matt Bannert
  • 27,631
  • 38
  • 141
  • 207
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Neat. I did follow the message first, but was distracted by the 'error' message when entering a gibberish package name for testing. So, 2 things in this answer were helpful to me: 1. `quietly = TRUE` 2. that github search hint. – Matt Bannert Jan 15 '18 at 16:17
  • 1
    _De nada_. Thanks for catching the missing paren in the code riff I left there. – Dirk Eddelbuettel Jan 15 '18 at 16:18