0x26res
0x26res

Reputation: 13902

Have R look for files in a library directory

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

Upvotes: 6

Views: 1315

Answers (4)

Jonathan
Jonathan

Reputation: 5278

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.

Upvotes: 1

Joshua Ulrich
Joshua Ulrich

Reputation: 176668

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.

Upvotes: 5

Gavin Simpson
Gavin Simpson

Reputation: 174813

Write your own source() wrapper?

mySource <- function(script, path = "~/r_lib/", ...) {
    ## paste path+filename
    fname <- paste(path, script, sep = "")
    ## source the file
    source(fname, ...)
}

You could stick that in your .Rprofile do is will be loaded each time you start R.

If you want to load all the R files, you can extend the above easily to source all files at once

mySource <- function(path = "~/r_lib/", ...) {
    ## list of files
    fnames <- list.files(path, pattern = "\\.[RrSsQq]$")
    ## add path
    fnames <- paste(path, fnames, sep = "")
    ## source the files
    lapply(fnames, source, ...)
    invisible()
}

Actually, though, you'd be better off starting your own private package and loading that.

Upvotes: 0

mropa
mropa

Reputation: 11842

Get all the files of your directory, in your case

d <- list.files("~/r_lib/")

then you can load them with a function of the plyr package

library(plyr)  
l_ply(d, function(x) source(paste("~/r_lib/", x, sep = "")))

If you like you can do it in a loop as well or use a different function onstead of l_ply. Conventional loop:

for (i in 1:length(d)) source(paste("~/r_lib/", d[[i]], sep = ""))

Upvotes: 0

Related Questions