0

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

2
  • So not just within the R/ directory, you mean? Commented Sep 25, 2014 at 18:24
  • @DavidRobinson exactly not just in folder. There are contained in different subfolders Commented Sep 25, 2014 at 18:49

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

If you set recursive to TRUE in list.files you can list all files with the pattern in all subfolders of a folder.
@aosmith - thank you! I've made an edit. Totally forgot list.files had a recursive argument
@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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.