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?
I've run into this myself on occasion where, for example, this works:
but this does not, under identical circumstances:
Your package presumably
Import
s the necessary dependency, but the various S3 methods, includingpredict.<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 addingrequireNamespace(<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 checkingmethods(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 loadranger
along with its various S3 methods, includingpredict.ranger()
, sopredict()
dispatches just fine.