Ask R to find files in the library directory

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

I would like to include these files, not using the full name, but simply "file.r". Basically I am looking for the same command as -I in the C ++ compiler.

Is there a way to install an include file from R in a .Rprofile or .Renviron file?

thanks

+6
linux r
source share
4 answers

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

 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 can use sys.source to avoid cluttering your global environment.

+5
source share

If you set the chdir parameter to TRUE , then the source calls inside the included file will refer to its path. Therefore, you can call:

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

It is probably best not to have source calls in your β€œlibrary” and make your code in a package, but sometimes it’s convenient.

+1
source share

Get all the files in your directory, in your case

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

then you can load them using the plyr package plyr

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

If you like, you can do this in a loop or use another function instead of l_ply . Normal loop:

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

Write your own source() packaging?

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

You can stick with what in your .Rprofile do will load every time you start R.

If you want to download all R files, you can easily expand this content to immediately download all files

 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() } 

In fact, you better start your own private package and download it.

0
source share

All Articles