Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have R look for files in a library directory

Tags:

linux

r

I am using R, on linux. I have a set a functions that I use often, and that I have saved in different .r script files. Those files are in ~/r_lib/.

I would like to include those files without having to use the fully qualified name, but just "file.r". Basically I am looking the same command as -I in the c++ compiler.

I there a way to set the include file from R, in the .Rprofile or .Renviron file?

Thanks

like image 288
0x26res Avatar asked Nov 29 '10 14:11

0x26res


2 Answers

You can use the sourceDir function in the Examples section of ?source:

sourceDir <- function(path, trace = TRUE, ...) {
   for (nm in list.files(path, pattern = "\\.[RrSsQq]$")) {
      if(trace) cat(nm,":")           
      source(file.path(path, nm), ...)
      if(trace) cat("\n")
   }
}

And you may want to use sys.source to avoid cluttering your global environment.

like image 116
Joshua Ulrich Avatar answered Sep 28 '22 06:09

Joshua Ulrich


If you set the chdir parameter of source to TRUE, then the source calls within the included file will be relative to its path. Hence, you can call:

source("~/r_lib/file.R",chdir=T)

It would probably be better not to have source calls within your "library" and make your code into a package, but sometimes this is convenient.

like image 45
Jonathan Avatar answered Sep 28 '22 04:09

Jonathan