0

I wrote a new S3 method in an R package, for a generic function 'NSE' from package 'hydroGOF', and I am unsure how to (let roxygen2) formulate the NAMESPACE.

Here is an example. 'NSE' has two required arguments, 'sim' and 'obs'.

#' @export
#' @importFrom hydroGOF NSE NSE.default
NSE.foo <- function(sim, obs, na.rm = TRUE, ...) {
  NSE.default(as.numeric(sim), as.numeric(obs), na.rm = TRUE, ...)
}

When i build the package, these rows are added to NAMESPACE:

S3method(NSE,foo)
importFrom(hydroGOF,NSE)
importFrom(hydroGOF,NSE.default)

My problem is now, that the (generic) function 'NSE' is not available when i load my package, and R throws an 'unknown function' error:

> library(mypackage)
> s <- rnorm(10)
> o <- rnorm(10)
> class(s) <- "foo"
> class(o) <- "foo"
> NSE(sim = s, obs = o)
Error: could not find function "NSE"

... unless I load 'hydroGOF' first, i which case it does what i want:

> library(hydroGOF)
> NSE(sim = s, obs = o)
[1] -1.195519

I understand that this has to do with hydroGOF functions being loaded but not attached when I attach my package, but I don't know how to solve this. There is no '@depends' roxygen directive which i could use rather than '@importFrom', or?

I suspect I arrived at "scenario 4" outlined by Hadley on his R-package/Namespace page:

A method for a generic in a suggested package. Namespace directives must refer to available functions, so they can not reference suggested packages. It’s possible to use package hooks and code to add this at run-time, but this is sufficiently complicated that I currently wouldn’t recommend it. Instead, you’ll have to design your package dependencies in a way that avoids this scenario.

... but i don't know how to avoid it. :)

Any help appreciated. Thanks!

renec
  • 1
  • 1
  • What about adding hydroGOF to the `Depends` field in the DESCRIPTION file ? – Tutuchan Mar 08 '16 at 11:11
  • Great, thanks @Tutuchan, I added it and now it does what I want. However, I still think that this is a bit "against the rules", since one best shouldn't use `Depends` for packages as i understand. I will go with this for the time being anyway, but if someone can clarify further, I would appreciate it. – renec Mar 08 '16 at 11:34
  • Also arrived at scenario 4. Any hints on how to do this? – Hannes Mühleisen Mar 11 '16 at 12:39

0 Answers0