Eugene Vlasov
Eugene Vlasov

Reputation: 53

Source a bunch of files in R script in a nice way

I have a script, let say main.R. I have a dozen of function files that I source in the main script. It looks like:

source('doThis.R')
source('doThat.R')
source('coolFun.R')
source('anotherFun.R')

...and so on. It is not a big problem but I would get rid of it. Should I just make a function sourceAll.R to source everything else and source it in my main.R? Or there are other ways to deal with functions?

Upvotes: 1

Views: 549

Answers (1)

Uwe
Uwe

Reputation: 42544

Occassionally, I find it less cumbersome to source some R files the sloppy way instead of creating a properly documented and maintained package (although the latter may pay off, especially when shared by many users).

This is what I have done in these cases:

file_names <- c(
  "doThis.R",
  "doThat.R",
  "coolFun.R",
  "anotherFun.R"
)
lapply(file_names, source)

You may pass arguments to source() as well, e.g.,

lapply(file_names, source, local = TRUE)

If all files to source are located in one directory, you may get the file names by simply calling list_files():

file_names <- list.files(path = "path_to_directory_of_R_files", pattern = "\\.R$")
lapply(file_names, source)

Upvotes: 3

Related Questions