January
January

Reputation: 17140

How to make a dependency optional in a package

I am coding a package in R which – among other things – can show plots with rgl. However, I found out with my students that rgl is a hassle: especially with those who use Macs. I end up spending a lot of time helping them to install RGL.

Is there a proper, CRAN sanctioned way to make the package optionally dependent on rgl? That if rgl cannot be loaded, some functions send a warning message and exit gracefully? How best should I do it?

EDIT: I know how to actually do it in a function; however, what I don't know is how to formally define it in the package requirements such that (i) CRAN doesn't complain, but (ii) rgl is formally specified as an optional dependency.

Upvotes: 6

Views: 652

Answers (1)

nicola
nicola

Reputation: 24510

Use requireNamespace in the definition of your functions that make use of rgl:

functionWithRgl<-function(...) {
   if (!requireNamespace("rgl", quietly = TRUE)) {
        warning("The rgl package must be installed to use this functionality")
        #Either exit or do something without rgl
        return(NULL)
    }
    #do stuff with rgl here prefixing it
    rgl::someRglFunction(someArguments)
    #...
}

In this way you don't need to declare rgl in the Depends or Import sections of the Description of your package.

Upvotes: 7

Related Questions