如何在我自己的函数中使用给定包的内部函数

时间:2017-12-14 15:39:30

标签: r namespaces r-package

我想使用给定R包的内部函数(例如httr)编写函数,而不必在函数的 body 中将这些方法称为httr:::method_of_httr_package(I不想使用:::)。

我尝试改变我的功能环境,例如:

enviroment(my_func) <- base::asNamespace("httr")

但它不起作用。

1 个答案:

答案 0 :(得分:1)

这通常不推荐,但假设您有特殊情况需要保证,或者为了回答所提出的字面问题:

my_func <- function(x) headers.response(x)
environment(my_func) <- asNamespace("httr")

# test
x <- list(headers = "X")
my_func(x)
## [1] "X"

my_func2 <- function(x) with(asNamespace("httr"), {
       headers.response(x)
})

# test
x <- list(headers = "X")
my_func2(x)
## [1] "X"

注意

根据具体情况,可以为该类创建一个新类和您自己的方法:

    # define our own response2 class method for headers
    headers.response2 <- function(x) paste(x$header, ":", x$header2)

    # test - create a response2 object and then run headers on it
    library(httr)
    x <- structure(list(header = "X", header2 = "Y"), class = "response2")
    headers(x)
    ## [1] "X : Y"

This will only work if you can control the input.
  • 这很麻烦,但您可以使用trace(有关详细信息,请参阅?trace)将代码插入到您没有编写的函数中。如果目标函数以与补丁不一致的方式发生变化但可以用作停止间隙,则可能会爆炸。在下面的示例中,我们只是在顶部打印出一条消息,但您可以在任何地方插入代码并使用函数的所有内部变量。

    library(httr)
    
    trace(httr:::headers.response, quote(print("Hello from headers.response")))
    x <- structure(list(headers = "X"), class = "response")
    headers(x)
    ## Tracing headers.response(x) on entry 
    ## [1] "Hello from headers.response"
    ## [1] "X"