Luyi Tian Luyi Tian -3 years ago 103
R Question

How to use a platform specific package in my R function

my R package has a function (

) that uses function(
) from another package (
) which only available on Unix. So I write my code this way, following the suggested packages in Writing R extension:

my_func = function(){
if (requireNamespace("foo", quietly = TRUE)) {
foo::bar(..) # also tried bar(...)
} else {
# do something else without `bar`

However, I keep getting such warning message when I run R CMD check:

'loadNamespace' or 'requireNamespace' call not declared from: foo

Is there any way to use platform specific packages without gives such warnings? I tried to include
in the Description file and the warning disappeared, but then the package cannot be installed on windows because
is not available for the win.

Answer Source

I think you misread that comment, though it is easy to do because the logic is not clear and incontrovertible.

In that first paragraph that talked about calling packages using require(package) they said it was OK for a test environment or vignette but not from inside a finished function to use library(package) or require(package).

This is considered bad form, because the packages you call inside a function will usurp the order of access your user has set up in her work environment when loading packages.

The method you use above:


is the approved of way to use a function within a function without altering the current environment.

But in order to use that function you must still have that package installed on your current machine or in your current working environment (such as a virtualenv or ipython or jupytr..and yes R will work in all those environments).

You cannot run a function that R cannot see from the working you must have it installed, but not necessarily loaded, to call it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download