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.
>
> 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") ) {
perhaps

    find(deparse(substitute(fun)), mode='function')

but note that this will *not* tell you whether *the* function you want
to import is already known, but rather whether *some* function with the
specified name is already known.

vQ

______________________________________________
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