Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change internal function of a package [duplicate]

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.

like image 874
Roland Avatar asked Aug 29 '12 13:08

Roland


2 Answers

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?

like image 107
Matt Dowle Avatar answered Oct 18 '22 07:10

Matt Dowle


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.

like image 45
Greg Snow Avatar answered Oct 18 '22 08:10

Greg Snow