Search code examples
rdependenciescran

Fallback and optional dependencies in R packages the CRAN way?


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?


Solution

  • 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.