简体   繁体   English

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

[英]How to use internal functions of a given package in my own functions

I want to write a function using internal functions of a given R package (for instance httr) without having to refer to these methods as httr:::method_of_httr_package in the body of my function (I do not want to use ::: ). 我想写使用给定的R包的内部函数的函数(例如HTTR),而不必把这些方法作为httr:::method_of_httr_package在我的函数 (我不想用::: )。

I try to change the environment of my function such as in: 我尝试更改功能的环境,例如:

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

but it does not work. 但它不起作用。

This is normally not recommended but assuming you have a special situation that warrants it or for sake of answering the literal question asked: 通常不建议这样做,但是假设您有特殊情况可以保证这样做或为了回答所问的字面问题:

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

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

or 要么

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

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

Note 注意

Depending on the specifics it may be possible to create a new class and your own method for that class: 根据具体情况,可能会创建一个新类以及该类的您自己的方法:

    # 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.
  • this is kludgy but you can use trace (see ?trace for details) to insert code into a function you didn't write. 这很麻烦,但是您可以使用trace (有关详细信息,请参见?trace )将代码插入未编写的函数中。 This can blow up on you if the target function changes in a manner not consistent with your patch but could be used as a stop gap. 如果目标功能以与补丁程序不一致的方式更改,但可以用作停止间隙,则可能会给您带来麻烦。 In the example below we just printed out a message at the top but you can insert the code anywhere and use all the internal variables of the function. 在下面的示例中,我们只是在顶部打印了一条消息,但是您可以在任意位置插入代码并使用该函数的所有内部变量。

     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" 

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

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