Skip to content

Instantly share code, notes, and snippets.

@constantAmateur
Created December 24, 2017 12:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save constantAmateur/cfea655803e72c84ec3979d2e5338893 to your computer and use it in GitHub Desktop.
Save constantAmateur/cfea655803e72c84ec3979d2e5338893 to your computer and use it in GitHub Desktop.
Function to make reusing R scripts easier
#' Imports a python style module. These are just files with .R/r extensions.
#'
#' If src is an R file, it is used directly. Otherwise the directories in searchDirs are searched for an R file named as \code{src}. The file is loaded into an environment that is stored in the callers environment.
#'
#' @param src File to load or name of module in search path.
#' @param as What to name the loaded module.
#' @param all Load all entries into parent namespace. Use with caution.
#' @param searchDirs Directories to search for module.
#' @param reattach If module is already loaded with all=TRUE, re-attach it.
import = function(src,as=NULL,all=FALSE,searchDirs=.modPaths,reattach=TRUE){
#Force it to be a character
src = as.character(substitute(src))
#Make a new environment for the src file
module = new.env()
#Get the thing
if(!file.exists(src)){
#Try and find the thing in each of the search paths
found=FALSE
for(searchDir in searchDirs){
if(file.exists(file.path(searchDir,sprintf('%s.r',src)))){
src = file.path(searchDir,sprintf('%s.r',src))
found=TRUE
break
}else if(file.exists(file.path(searchDir,sprintf('%s.R',src)))){
src = file.path(searchDir,sprintf('%s.R',src))
found=TRUE
break
}
}
if(!found)
stop(sprintf("Could not find module %s on search path.",src))
}
#Load it into our new environment
sys.source(src,envir=module,keep.source=interactive())
#Work out what to call it
if(is.null(as))
as=gsub('\\.[Rr]$','',basename(src))
#Now do the assignment
if(all){
nom = sprintf("module:%s",as)
if(nom %in% search()){
if(reattach){
detach(pos=match(nom,search()))
}else{
stop(sprintf("A module named %s is already attached.",as))
}
}
attach(module,pos=2,name=nom)
}else{
penv = parent.frame()
assign(as,module,envir=penv)
}
invisible(NULL)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment