[R] how to avoid infinite loops when sourcing R files

Adrian Dragulescu adrian_d at eskimo.com
Wed May 9 23:58:08 CEST 2007


Hello,

I have a bunch of R files in a directory and I want to source all of them
with something like lapply(files, source).

I have a main.R file
source("C:/Temp/set.parms.R")
parms <- set.parms()
do.calcs(parms)
cat("I'm done with main.R\n")

Then I have set.parms.R function
set.parms <- function(){
  cat("I'm in set.parms.\n"); flush.console()
  directory <- "C:/Temp/"
  files <- dir(directory, "\\.[rR]$", full.name=T)
  files <- files[-grep("set.parms.R", files)]     # remove infinite loop
  lapply(files, source)  # source them all

  cat("Exiting set.parms.\n"); flush.console()
}

And other functions f1, f2, f3, etc. in the same directory that also
source set.parms.R.  For example:
f1 <- function(){
  source("H:/user/R/RMG/Energy/VaR/Overnight/Test/set.parms.R")
  cat("I add two numbers.\n"); flush.console()
}

Because of the source command in f1, I get into an infinite loop.  This
must be a common situation but I don't know how to avoid it.
I need the source(set.parms) in f1, f2, f3, etc. because I want use a
different combination of them in other projects.


Thanks,
Adrian



More information about the R-help mailing list