Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Source function by name/Import subset of functions

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")  
like image 410
Brad Avatar asked Apr 15 '14 19:04

Brad


People also ask

What does source () do R?

source causes R to accept its input from the named file or URL or connection or expressions directly. Input is read and parse d from that file until the end of the file is reached, then the parsed expressions are evaluated sequentially in the chosen environment.

How do I run an R script from another R script?

You can execute R script as you would normally do by using the Windows command line. If your R version is different, then change the path to Rscript.exe. Use double quotes if the file path contains space.


1 Answers

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.

like image 104
andybega Avatar answered Sep 24 '22 17:09

andybega