On 22/03/2009 5:05 PM, JiHO wrote:
Hello everyone,

I often create some local "libraries" of functions (.R files with only functions in them) that I latter call. In scripts that call a function from such library, I would like to be able to test whether the function is already known in the namespace and, only if it is not, source the library file. I.e. what `require` does for packages, I want to do with my local functions.

That's pretty hard to make bulletproof. Why not just put those functions in a package, and use that package? If the functions are all written in R, creating the package is very easy: see package.skeleton. (And if you have a perfect memory and don't plan to distribute the package to anyone, you can skip documenting the functions: then it's almost no work at all.)

Duncan Murdoch


Example:
lib.R
        foo <- function(x) { x*2 }

script.R
        require.local(foo,"lib.R")
# that searches for function "foo" and, if not found, executes source("lib.R")
        foo(2)

Obviously, I want the test to be quite efficient otherwise I might as well source the local library every time. I am aware that it would probably not be able to check for changes in lib.R (i.e. do complicated things such as re-source lib.R if foo in the namespace and foo in lib.R are different), but that I can handle manually.

This seems like a common enough workflow but I cannot find a pre- existing solution. Does anyone have pointers?

Otherwise I tried to put that together:

require.local <- function(fun, lib)
#
#       Searches for function "fun" and sources "lib" in
#       case it is not found
#
{
if (! (deparse(substitute(fun)) %in% ls(".GlobalEnv") && class(fun) == "function") ) {
                cat("Sourcing", lib,"...\n")
                source(lib)
        }
}

but I am really not confident with all those deparse/substitute things and the environment manipulation, so I guess there should be a better way.

JiHO
---
http://jo.irisson.free.fr/

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to