Question

I am trying to source multiple functions, that differ by a number in the name.

For example: func1, func2.

I tried using "func_1", and "func_2", as well as putting the number first, "1func" and "2func". No matter how I index the function names, the source function just reads in one function that it calls "func" - which is not what I want.

I have tried using for-loops and sapply:

for-loop:

func.list <- list.files(path="/some_path",pattern="some pattern",full.names=TRUE)
for(i in 1:length(func.list)){
source(func.list[i])
}

sapply:

sapply(func.list,FUN=source)

I am going to be writing multiple versions of a data correction function, and would really like to be able to index them - because giving a concise, but specific, name would be difficult, and not allow me to selectively source just the function files from their directory.

In my code, func.list gives the output (I have replaced the actual directory because of privacy/contractual issues):

[1] "mypath/1resp.correction.R" 
[2] "mypath/2resp.correction.R"

Then when I source func.list with either the for-loop or sapply code (listed above), R only loads one function named resp.correction, with the code body from "2resp.correction.R".

Était-ce utile?

La solution

The argument to source is a file name, not a function name. So you cannot be fancy here: you need to provide the exact filenames.

It sounds like your two files contain the definitions of a function with the same name (resp.correction) in both files, so yes, as you source one file after the other, the function is overwritten in your global environment.

You could, inside your loop, reassign the function to a different name:

func.list <- list.files(path="/some_path",pattern="some pattern",full.names=TRUE)
for(i in 1:length(func.list)) {
   source(func.list[i], local = TRUE)
   assign(paste0("resp.correction", i), resp.correction, envir = .GlobalEnv)
} 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top