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
1 Answer
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)
3 Comments
aosmith
If you set
recursive to TRUE in list.files you can list all files with the pattern in all subfolders of a folder.Rich Scriven
@aosmith - thank you! I've made an edit. Totally forgot
list.files had a recursive argumentmert
@RichScriven I tried to extend your
sourceFolder function to source the cpp files via the command Rcpp::sourceCpp but failed. Is it possible to extend your function to cpp files?
R/directory, you mean?