I am using a R package, in which there are 2 functions f1 and f2 (with f2 calling f1)
I wish to overwrite function f1.
Since R 2.15 and the mandatory usage of namespace in packages, if I just source the new function, it is indeed available in the global environement (ie. just calling f1(x) in the console returns the new result). However, calling f2 will still use the packaged function f1. (Because the namespace modifies the search path, and seals it as explained here in the Writing R Extensions tutorial)
What is the proper way to completely replace f1 with the new one? (apart from building again the package!) This can be useful in several situations. For instance if there is a bug in a package that you have not developed. Or if you don't want to re-build your packages everyday while they are still under development.
I know about function
assignInNamespace("f1",f1,ns="mypackage")
However, the help page ?assignInNamespace
is a bit enignmatic and seems to discourage people from using it without giving more information, and I couldn't find any best practice recommendations on the official CRAN tutorial. and after calling this function:
# Any of these 2 calls return the new function
mypackage::f1
getFromNamespace(x = "f1", envir = as.environment("package:mypackage"))
# while this one still returns the old packaged version
getFunction(name = "f1", where = as.environment("package:mypackage"))
This is very disturbing. How is the search path affected?
For now I am doing some ugly things such as modifying the lockEnvironment
function so that library
doesn't lock the package namespace, and I can lock it at a later stage once I have replaced f1 (which seems really not a good practice)
So basically I have 2 questions:
- what does exactly do
assignInNamespace
in the case of a package namespace (which is supposed to be locked) - What are the good practices?
many thanks for sharing your experience there.
EDIT: people interested in this question might find this blog post extremely interesting.