Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :::).

I try to change the environment of my function such as in:

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

but it does not work.

like image 521
Etienne Kintzler Avatar asked Dec 20 '25 22:12

Etienne Kintzler


1 Answers

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. 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"
    
like image 103
G. Grothendieck Avatar answered Dec 22 '25 12:12

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!