Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load all files from folder and subfolders

Tags:

r

I know about the source() in R. It takes a path and/or filename to load i.e. a function which is saved in another .R file. What I need is basically the same command, but it is supposed to load every .R file from one folder and its subfolders.

Is there a oneliner (some library) or would I have to write a loop 'n everything?

like image 990
Stophface Avatar asked Sep 30 '15 09:09

Stophface


3 Answers

This might work

lapply(list.files(pattern = "[.]R$", recursive = TRUE), source)
like image 177
Koundy Avatar answered Oct 21 '22 11:10

Koundy


In R help of the library, you can find the following:

   ## If you want to source() a bunch of files, something like
  ## the following may be useful:
   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")
      }
    }
like image 2
arodrisa Avatar answered Oct 21 '22 10:10

arodrisa


You could use a simple recursive function like

sourceRecursive <- function(path = ".") {
  dirs <- list.dirs(path, recursive = FALSE)
  files <- list.files(path, pattern = "^.*[Rr]$", include.dirs = FALSE, full.names = TRUE)
  for (f in files)
    source(f)
  for (d in dirs)
    sourceRecursive(d)
}
like image 1
Tim Avatar answered Oct 21 '22 12:10

Tim