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")
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With