Run every file in a folder

r

Solution

I have the following function in my utils file:

## finds all .R files within a folder and soruces them
sourceEntireFolder <- function(folderName, verbose=FALSE, showWarnings=TRUE) { 
  files <- list.files(folderName, full.names=TRUE)

  # Grab only R files
  files <- files[ grepl("\\.[rR]$", files) ]

  if (!length(files) && showWarnings)
    warning("No R files in ", folderName)

  for (f in files) {
    if (verbose)
      cat("sourcing: ", f, "\n")
    ## TODO:  add caught whether error or not and return that
    try(source(f, local=FALSE, echo=FALSE), silent=!verbose)
  }
  return(invisible(NULL))
}

Problem

Can I write one R script to open and run every R file in a folder? I know how to check for the presence of a file in a folder, how to read every file in a folder as a text connection and how to read every data file in a folder. However, I want to execute every R script in a folder one at a time, ideally using a single R script and the default R gui installed on a Windows desktop during installation. I suspect I might need to run R from the command line instead and write some sort of batch file to do this. I have rarely run R from the command line and never written a batch file for R. Here are some example R scripts all stored in a folder named `run_all_these`: The file `run.one.r` contains: ``` a <- 10 b <- 20 c <- a+b c ``` The file `run.two.r` contains: ``` a <- 10 b <- 20 c <- a-b c ``` The file `run.three.r` contains: ``` a <- 10 b <- 20 c <- a*b c ``` The file `run.four.r` contains: ``` a <- 10 b <- 20 c <- a/b c ``` I found virtually nothing on this topic using Google. Although, I did find a little on batch files here: http://cran.r-project.org/bin/windows/base/rw-FAQ.html My actually R scripts will each create their own output files when run. So, I am mostly concerned with running the R scripts right now. Although the next step would be to open each R script, change `a` from `10` to `100` and run them again. Perhaps that should be a follow-up post. Thank you for any suggestions. EDIT Nov 20, 2013: After discussion with Ricardo Saporta below I changed the four input files to: File `run.one.r`: ``` a <- 10 b <- 20 c <- a+b print(c) ``` File `run.two.r`: ``` a <- 10 b <- 20 c <- a-b print(c) ``` File `run.three.r`: ``` a <- 10 b <- 20 c <- a*b print(c) ``` File `run.four.r`: ``` a <- 10 b <- 20 c <- a/b print(c) ```

Original source