I\'ve created a utility R script, util.R, which I want to use from other scripts in my project. What is the proper way to ensure that the function this script defines are av
Say util.R produces a function foo(). You can check if this function is available in the global environment and source the script if it isn't:
if(identical(length(ls(pattern = "^foo$")), 0))
source("util.R")
That will find anything with the name foo. If you want to find a function, then (as mentioned by @Andrie) exists() is helpful but needs to be told exactly what type of object to look for, e.g.
if(exists("foo", mode = "function"))
source("util.R")
Here is exists() in action:
> exists("foo", mode = "function")
[1] FALSE
> foo <- function(x) x
> exists("foo", mode = "function")
[1] TRUE
> rm(foo)
> foo <- 1:10
> exists("foo", mode = "function")
[1] FALSE