简体   繁体   English

如何在全局环境中加载包的内部功能

[英]How to load package's internal function in global environment

I have a package whose internal functions I want to load in the global environment. 我有一个包,其内部函数我想在全局环境中加载。 The only way I can think of is to do it manually, ie 我能想到的唯一方法是手动完成,即

f <- packageName:::someInternalFunction

For all internal functions. 适用于所有内部功能。 I'm guessing there's an easier way to do it, but how? 我猜这是一种更简单的方法,但是怎么做? Thanks in advance. 提前致谢。

You could do the following: 您可以执行以下操作:

library(pacman)

pack.name <- "qdap"

hidden <- setdiff(p_funs(pack.name, TRUE), p_funs(pack.name))

invisible(lapply(hidden, function(x) {

    a <- strtrim(x, 1) == "%" 
    b <- substring(x, nchar(x)) == "%"

    if (a && b) {
        x2 <- paste0("`", x, "`")
    } else {
        x2 <- x
    }

    assign(x, eval(parse(text=paste0(pack.name, ":::", x2))), 
        envir = .GlobalEnv)
}))

Use package pacman as an example: 使用package pacman作为示例:

attach(loadNamespace("pacman"), name = "pacman_all")

Now all its unexported functions are available. 现在所有未导出的功能都可用。 You can see the attached "pacman_all" with search() . 您可以使用search()查看附加的“pacman_all”。

To revert, run detach("pacman_all") . 要恢复,请运行detach("pacman_all")

  1. download the tar.gz with the source code for the package from CRAN and extract 从CRAN下载带有源代码的tar.gz并解压缩
  2. rename to "mypackage" (eg) in the DESCRIPTION 在描述中重命名为“mypackage”(例如)
  3. modify its NAMESPACE to export all that you need 修改其NAMESPACE以导出您需要的所有内容
  4. install.package(<path to mypackage>, type="source", repos=NULL)
  5. library("mypackage")

You of course realize that relying on somebody else's internal functions is very dangerous as the behavior of these functions is liable to change without warning (that's one reason they're internal). 你当然意识到依赖别人的内部功能是非常危险的,因为这些功能的行为在没有警告的情况下容易改变(这是他们内部的一个原因)。 installing your own modified version of the package goes some way towards reducing that danger as it gives you more control over the code you're calling. 安装你自己的软件包修改版本可以减少这种危险,因为它可以让你更好地控制你正在调用的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM