Try this: if (!exists("myfun", mode = "function")) source("myfile.R")
Also check the other arguments of exists in case you want to restrict the search. On Sun, Mar 22, 2009 at 5:05 PM, JiHO <jo.li...@gmail.com> 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") ) { > 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.