How to include (source) R script in other scripts

前端 未结 6 903
夕颜
夕颜 2020-12-12 12:10

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

6条回答
  •  天命终不由人
    2020-12-12 12:20

    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
    

提交回复
热议问题