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?
This might work
lapply(list.files(pattern = "[.]R$", recursive = TRUE), source)
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")
}
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With