Reputation: 3030
I'm working on a custom R package (it is private, not hosted anywhere). In this package, I have a function that takes xgboost, RandomForest (from the ranger function), and glmnet models and uses them to predict on a new dataset.
Each time I'm predicting, I use the same generalized predict function. If I don't namespace the function, R doesn't know which library to use for the predict.
The error I get is:
Error in UseMethod("predict") :
no applicable method for 'predict' applied to an object of class "c('lognet', 'glmnet')"
If I load the functions manually, it works, but I know that loading packages manually within an R library is a taboo.
I tried using glmnet::glmnet.predict, etc. but this is giving me errors, as well. What would be the proper way to namespace these predict functions to avoid loading the libraries manually?
Upvotes: 6
Views: 1043
Reputation: 865
I've run into this myself on occasion where, for example, this works:
ranger::predictions(predict(model, data))
but this does not, under identical circumstances:
predict(model, data)
Your package presumably Import
s the necessary dependency, but the various S3 methods, including predict.<class>()
, are never registered for use unless you tell R to use them at some point earlier in your program. You can fix this by adding requireNamespace(<package name>, quietly = TRUE)
either at the top of the given function or in .onLoad()
. This causes R to register the appropriate S3 methods, etc., and you can confirm this by checking methods(predict)
before and after. Importantly, this is true for non-exported methods that disallow roxygen2 declarations like #' @importFrom <package name> <predict.class>
.
In my particular example above, ::
causes R to load ranger
along with its various S3 methods, including predict.ranger()
, so predict()
dispatches just fine.
Upvotes: 2