[R] 'require' equivalent for local functions

JiHO jo.lists at gmail.com
Sun Mar 22 22:05:13 CET 2009

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.

	foo <- function(x) { x*2 }

	# that searches for function "foo" and, if not found, executes  

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")

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


More information about the R-help mailing list