问题描述
我正在处理自定义R程序包(它是私有的,不在任何地方托管).在此程序包中,我有一个函数,该函数接受xgboost,RandomForest(来自Ranger函数)和glmnet模型,并使用它们对新数据集进行预测.
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.
每次进行预测时,我都使用相同的广义预测功能.如果我没有为函数命名空间,则R不知道要使用哪个库进行预测.
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.
我得到的错误是:
Error in UseMethod("predict") :
no applicable method for 'predict' applied to an object of class "c('lognet', 'glmnet')"
如果我手动加载功能,它可以工作,但是我知道在R库中手动加载软件包是禁忌.
If I load the functions manually, it works, but I know that loading packages manually within an R library is a taboo.
我尝试使用glmnet :: glmnet.predict等,但这也给了我错误.为了避免手动加载库,对这些预测函数进行命名空间的正确方法是什么?
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:
ranger::predictions(predict(model, data))
但这在相同情况下不会:
but this does not, under identical circumstances:
predict(model, data)
您的程序包大概是Import
所必需的依赖项,但是各种S3方法(包括predict.<class>()
)都不会注册使用,除非您告诉R在程序中的某个早些时候使用它们..您可以通过在给定函数的顶部或.onLoad()
中添加requireNamespace(<package name>, quietly = TRUE)
来解决此问题.这会导致R注册适当的S3方法等,您可以通过前后检查methods(predict)
来确认.重要的是,这对于不允许使用roxygen2声明(例如#' @importFrom <package name> <predict.class>
)的 non-exported 方法是正确的.
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>
.
在上面的特定示例中,::
导致R加载ranger
及其各种S3方法(包括predict.ranger()
),因此predict()
可以很好地进行分派.
In my particular example above, ::
causes R to load ranger
along with its various S3 methods, including predict.ranger()
, so predict()
dispatches just fine.
这篇关于如何从相同的自定义R包函数调用对3种不同算法的预测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!