Reputation: 2022
I have a question about sourcing R scripts in different folders. Suppose I created a new project in R Studio. The project folder contains several folders (data, different folders containing the scripots, latex folder, plot folder etc). Is there a way to automatically source all R scripts within this project folder? Thanks
Upvotes: 0
Views: 2855
Reputation: 99371
I use this function for sourcing all R files in a specific folder.
## finds all .R and .r files within a folder and sources them
sourceFolder <- function(folder, recursive = FALSE, ...)
{
files <- list.files(folder, pattern = "[.][rR]$",
full.names = TRUE, recursive = recursive)
if (!length(files))
stop(simpleError(sprintf('No R files in folder "%s"', folder)))
src <- invisible(lapply(files, source, ...))
message(sprintf('%s files sourced from folder "%s"', length(src), folder))
}
So, if I have a folder on my desktop named Rfiles
I can source all the files with a .r
or .R
extension with the call
sourceFolder("./Desktop/Rfiles")
# 6 files sourced from folder "./Desktop/Rfiles"
You could use the recursive
argument to source all the R files in the subdirectories
sourceFolder("yourFolder", recursive = TRUE)
Upvotes: 2