R: Source function by name / Import a subset of functions

advertisements

I have a question with importing functions.

Say I have a R script named "functions" which looks like this:

mult <- function(x,y){

   return(x*y)

}

divide <- function(x,y){

   return(x/y)

}

Currently I am importing all functions in the script:

source(file="C:\\functions.R",echo=FALSE)

The problem is that the (actual) R script is getting very large.

Is there a way to import the "mult" function only?

I was looking at evalSource/insertSource but my code was not working:

insertSource("C:\\functions.R", functions="mult")


It looks like your code will work with a slight change: define an empty object for the function you want to load first, then use insertSource.

mult <- function(x) {0}
insertSource("C:\\functions.R", functions="mult")
mult

Which gives:

Object of class "functionWithTrace", from source
function (x, y)
{
    return(x * y)
}

## (to see original from package, look at object@original)

The mult object has some additional information that I suppose is related to the original application for insertSource, but you could get rid of them with mult <- [email protected], which will set mult to the actual function body only.

Also, you might be interested in the modules project on github, which is trying to implement a lightweight version of R's package system to facilitate code reuse. Seems like that might be relevant, although I think you would have to split your functions into separate files in different subdirectories.