Skip to content

Instantly share code, notes, and snippets.

@squito
Last active June 13, 2019 19:09
Show Gist options
  • Save squito/c1a094b1aee0fe6e84cf to your computer and use it in GitHub Desktop.
Save squito/c1a094b1aee0fe6e84cf to your computer and use it in GitHub Desktop.
searchable source dirs for R (aka, a "classpath" for R)
## this should get loaded by your ~/.Rprofile
## either just stick all these definitions right in ~/.Rprofile, or
## have ~/.Rprofile source this file, etc.
source.dirs <- c(
## add any "base" locations here. this is like a "classpath" in java
## my default is c("~/myRUtils/src","~/companyRUtils/src","~/publicRUtils"),
## but you can use whatever you like
paste(Sys.getenv("HOME"),"myRUtils","src", sep="/"),
paste(Sys.getenv("HOME"),"companyRUtils","src", sep="/"),
paste(Sys.getenv("HOME"),"publicRUtils", sep="/")
)
mylib <- function(lib, path=source.dirs, verbose=T){
## use this to search for a file in source.dirs (aka, your R "classpath")
for(p in path) {
cand = paste(p, lib, sep="/")
if(file.exists(cand)) {
if(verbose)
print(paste("found", cand))
source(cand)
return(invisible(cand))
}
}
print(paste("couldn't find ", lib, " in any of : ", path))
return(invisible(NULL))
}
## say I've set my "source.dirs" to
## c("~/myRUtils/src","~/companyRUtils/src","~/publicRUtils")
## first, I want to load a "~/companyRUtils/src/io/fileUtils.R". The idea is,
## this file is shared inside our company (hopefully in version control).
## Everyone can load the file the same way, as long as the setup the base part
## of their "classpath" appropriately
mylib("io/fileUtils.R")
## now I want to load one of my scripts that is still a little too hacky to even
## be worth sharing internally, but its still useful to me, so I dropped it in
## "~/myRUtils/src/plotsUtils.R"
mylib("plotUtils.R")
## finally, I've pulled some assorted R scripts into my "~/publicRUtils" dir --
## maybe even from github. I can easily load them up as well. Note that
## "~/publicRUtils is *last* in my `source.dir`, so it if there is another file
## with this name in "~/myRUtils/src" or "~/companyRUtils/src", that would get
## used instead
mylib("somebodysAwesomeHelperFunctionsButThatArentInAPackage.R")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment