How to include (source) R script in other scripts

前端 未结 6 908
夕颜
夕颜 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:29

    Here is a function I wrote. It wraps the base::source function to store a list of sourced files in a global environment list named sourced. It will only re-source a file if you provide a .force=TRUE argument to the call to source. Its argument signature is otherwise identical to the real source() so you don't need to rewrite your scripts to use this.

    warning("overriding source with my own function FYI")
    source <- function(path, .force=FALSE, ...) {
      library(tools)
      path <- tryCatch(normalizePath(path), error=function(e) path)
      m<-md5sum(path)
    
      go<-TRUE
      if (!is.vector(.GlobalEnv$sourced)) {
        .GlobalEnv$sourced <- list()
      }
      if(! is.null(.GlobalEnv$sourced[[path]])) {
        if(m == .GlobalEnv$sourced[[path]]) {
          message(sprintf("Not re-sourcing %s. Override with:\n  source('%s', .force=TRUE)", path, path))
          go<-FALSE
        }
        else {
          message(sprintf('re-sourcing %s as it has changed from: %s to: %s', path, .GlobalEnv$sourced[[path]], m))
          go<-TRUE
        }
      } 
      if(.force) {
        go<-TRUE
        message("  ...forcing.")
      }
      if(go) {
        message(sprintf("sourcing %s", path))
        .GlobalEnv$sourced[path] <- m
        base::source(path, ...)
      }
    }
    

    It's pretty chatty (lots of calls to message()) so you can take those lines out if you care. Any advice from veteran R users is appreciated; I'm pretty new to R.

提交回复
热议问题