Change internal function of a package [duplicate]
Asked Answered
E

2

17

Some background:

I have to use function HMR from package HMR a lot. Unfortunately, this function is very slow. (HMR is essentially a fitting function, which is designed to be as robust as possible, which is one reason for the lack of efficiency.) Function HMR calls function HMR::.HMR.fit1, which does the actual fitting. Using Rprof I know that the main problem regarding efficiency is the use of lsfit, which gets called a lot. Therefore, I modified the code of .HMR.fit1 to call the C function used by lsfit directly without all the overhead of lsfit, which should result in a substantial speed gain.

Now I would like to substitute HMR::.HMR.fit1 with my modified function and test HMR if it gives the same results and how much speed I gain.

I tried to do this:

mod.fun <- function(<many args>) {
 <a lot of code>
}
environment(mod.fun) <- environment(.HMR.fit1)
.HMR.fit1 <- mod.fun 

However, HMR::.HMR.fit1 is not changed by doing this and apparently HMR::HMR does not use my modified fitting function. Is there a way to achieve what I want without building the package from source, which I cannot do due to user rights restrictions on my (windows) computer?

Right now, my solution would be to copy the code of HMR::HMR, but I hope there is a more convenient solution.

Emptyhanded answered 29/8, 2012 at 13:14 Comment(0)
M
21

Try

?assignInNamespace

to replace .HMR.fit1 in the HMR package with your version.

Possible duplicate of :

How do I override a non-visible function in the package namespace?

Mitzvah answered 29/8, 2012 at 13:26 Comment(1)
If you want to add new function instead of modifying the old, use this solution: https://mcmap.net/q/396845/-add-objects-to-package-namespaceFoliose
C
8

For a quick testing you can use the trace function with edit=TRUE to modify the function, this will do the replacing in the proper namespace and also allow you to use untrace to revert the function back to the original. These changes will not last beyond the current session.

Combined answered 29/8, 2012 at 14:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.